开发者

cakephp - has many through not saving

I have the following has m开发者_运维技巧any through relationship

Alert            AlertsElement       Search 
 id               id                  id 
 name             alert_id            link 
                  search_id
                  ordering

Here are my models

class Alert extends AppModel {
var $name = 'Alert';
var $hasMany = array('AlertsElement');  

class AlertsElement extends AppModel {
var $name = 'AlertsElement';
var $belongsTo = array('Alert','Search');

class Search extends AppModel {
var $name = 'Search';
var $hasMany = array('AlertsElement');

Here is my test code I am using to do a save -

$d = array();
$d['Alert']['id'] = 1976;
$d['Search']['id'] = 107;
$d['AlertsElement']['ordering'] = 2;
$this->Alert->create();
$this->Alert->saveAll($d);

I get this error -

Cannot use a scalar value as an array [CORE/cake/libs/model/model.php, line 1696]

and a row entry in alertselement with the order but the foreign keys set to 0

Any ideas ?

Thanks, Alex


In order to save a hasMany relationship with saveAll, the hasMany-associated model data (in this case, $d['AlertsElement']) needs to be an indexed array of associative arrays, thus:

$d = array(
  'Alert' => array(
    'id' => 1976
  ),
  'AlertsElements' => array(
    0 => array(
      'ordering' => 2
    ) 
  )
);
$this->Alert->saveAll($d);

Note that the associative array, consisting of the 'ordering' key and its value, has been shifted down into an indexed array. This is the required format for saving hasMany-associated data in a single saveAll operation, because this format expands gracefully whether you want to save one or ten associated records.

Refer to the Cake manual on saving related model data for more info.


I got here looking for a solution to this question. Not to contradict Daniel, the book says that when you use a hasMany through relationship (which is what Alex is using), you can save all three records with a single saveAll call, but you do it from the joining table's model like this:

$data = array(
    [Student] => Array
        (
            [first_name] => Joe
            [last_name] => Bloggs
        )

    [Course] => Array
        (
            [name] => Cake
        )

    [CourseMembership] => Array
        (
            [days_attended] => 5
            [grade] => A
        )

);
$this->CourseMembership->saveAll($data);

Unless I've misread the book, that example should create the Student, Course, and joining CourseMembership records. That said, I have yet to be able to get it to work as documented. I'm passing in an id for the Course as I'm using an existing Course, but it doesn't create the Student or the CourseMembership record.

Any more feedback appreciated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜