Cake php, sql error 150


Cake php, sql error 150

在发布问题/代码之前,我将介绍一下我正在做的事情。目前我正在开发一个使用cakepp和mysql的网站。我有一个登录系统,用户可以登录,每个用户都可以创建一个团队。当用户创建团队时,他们被视为团队负责人。我的数据库中有两个表。一个用于用户,另一个用于团队。在teams表中,有一个名为user_id的字段,它表示创建团队的用户。它是一个foriegn键,链接到User表中名为id的字段。

因此,当用户创建团队时,我希望我的程序自动识别领导者的id,并将其保存为团队模型中的user_id,该模型将进入我的表中。

这是我在团队模型类中的代码

<?php
class TeamsController extends AppController {
public $name = 'Teams';
public function add() {
    if ($this->request->is('post')) {
                    //THIS LINE SETS THE TEAM LEAD
        $this->Team->set('user_id', $this->Auth->user('id'));
        echo $this->Auth->user('id');
        if ($this->Team->save($this->request->data)) {
            $this->Team->set('user_id', $this->Auth->user('id'));
            $this->Session->setFlash('The team  has been saved');
            $this->redirect(array('controller' => 'Users','action' => 'index'));
        } else {
            $this->Session->setFlash('The team could not be created. Please, try again.');
        }
    }
}   

正如您所看到的,我正在从当前用户模型中获取user_id,并将其放入团队模型中。

然而,当我这样做的时候,我不断得到一个mysql错误150,这与foriegn键约束有关。我不知道为什么会发生这种事。我检查并交叉引用了这两个表中的所有数据,数据都在这两个表格中!两个表都是Innodb,两个字段都是int,不接受null。

<?php
   class TeamsController extends AppController {
    public $name = 'Teams';
   public function add() {
    if ($this->request->is('post')) {
                //THIS LINE SETS THE TEAM LEAD
    $this->request->data['Team']['user_id']= $this->Auth->user('id');

    if ($this->Team->save($this->request->data)) {
        $this->set('user_id', $this->Auth->user('id'));
        $this->Session->setFlash('The team  has been saved');
        $this->redirect(array('controller' => 'Users','action' => 'index'));
    } else {
        $this->Session->setFlash('The team could not be created. Please, try again.');
    }
   }
} 

您的代码应该看起来像:

您的控制器代码:

<?php
class TeamsController extends AppController {
public $name = 'Teams';
public function add() {
  if ($this->request->is('post')) {
    $team_details = $this->request->data;
    $team_details['Team']['user_id'] = $this->Auth->user('id');
    if ($this->Team->save($team_details)) {
        $this->Session->setFlash('The team  has been saved');
        $this->redirect(array('controller' => 'Users','action' => 'index'));
    } else {
        $this->Session->setFlash('The team could not be created. Please, try again.');
    }
  }
}