开发者

Manually packaging data for CakePHP's save()

I'm trying to package up some data for the save() function in cakephp. I'm new to PHP, so I'm confu开发者_JS百科sed about how to actually write the below in code:

Array
(
    [ModelName] => Array
        (
            [fieldname1] => 'value'
            [fieldname2] => 'value'
        )
)

Thank you!


To answer your question, you can create the array structure you need, and save it, by doing this:

<?php
$data = array(
    'ModelName' => array(
        'fieldname1' => 'value',
        'fieldname2' => 'value'
    )
);
$this->ModelName->save($data);
?>

Please note: Based on what you've written above in your comments it looks like you're not keeping to the CakePHP conventions. It's possible to do things this way but you'll save yourself a lot of time and trouble if you decided to stick with the CakePHP defaults as much as possible, and only do it your own way when you have a good reason to.

A couple things to remember are:

  1. Model names should be singular. This means that your model should be called Follower instead of Followers.
  2. The model's primary key in the database should be named just id, not followers_id, and should be set as PRIMARY KEY and AUTO_INCREMENT in your database.

If you decide not to follow the conventions you'll probably find yourself scratching your head, wondering why things aren't working, every step of the way. Try having a look at the CakePHP documentation for more details.


I think you need to do like below:

$this->Followers->create();
$this->data['Followers']['user_id'] = $user_id;

$this->data['Followers']['follower_id'] = $follower_id; // If it is primary and auto increment than you don't need this line.

$this->Followers->save($this->data)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜