简体   繁体   中英

Problems creating a HABTM record in CakePHP

I have a problem with creating a HABTM record in my CakePHP application. Basically, I have objects that a user can like, exactly the same as Facebook. The three tables are:

  • users
  • objects
  • objects_users

I'm trying to create a HABTM record with the following code:

$data = array(
    'Object' => array(
        'id' => $object_id
    ),
    'User' => array(
        'id' => $this->Auth->user('id')
    )
);
$this->Object->User->save($data);

But I keep getting the following error message:

Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( dbprefix . objects_users , CONSTRAINT objects_users_ibfk_2 FOREIGN KEY ( user_id ) REFERENCES users ( id ) ON DELETE CASCADE ON UPDATE CASCADE)

How do I create a HABTM record programatically in my controller when I know the two relavant IDs?

If you have the table 'objects_users' then the HABTM Model between Object and User will be called ObjectsUser.

You can creat a record in the objects_users table using following code:

$data = array();
$data['ObjectsUser']['user_id'] = $user_id;
$data['ObjectsUser']['object_id'] = $object_id;

// From Users Controller use following code to insert the document
$this->User->ObjectsUser->save($data);

// From Objects Controller use
$this->Object->ObjectsUser->save($data);

For the two above inserts to work you must have the relationship defined in one of the two Models like this:

// In User.php Model
public $hasAndBelongsToMany = 'Object';

// In Object.php Model
public $hasAndBelongsToMany = 'User';

Let me know if this works for you.

The error message indicates that the User-id you provided does not exist in the users table.

Check the data that your're trying to save via:

debug($data);

And check your SQL statements from the debug panel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM