dsuikgi9199 2013-04-08 19:24
浏览 41
已采纳

在CakePHP中创建HABTM记录时出现问题

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?

  • 写回答

2条回答 默认 最新

  • dongxi8297 2013-04-08 19:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题