CakePHP 3:保存新实体(错误:完整性约束违规)

时间:2016-12-27 18:08:09

标签: php mysql cakephp cakephp-3.0

我制作了一个新的cakephp应用程序,但我有几天的错误。

这是数据库结构:

Articles:
id | title | user1 | user2
--------------------------

Users:
id | username | email
----------------------

ArticlesTable.php:

class ArticlesTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->table('Articles');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->belongsTo('User1', [
           'className' => 'Users',
           'joinType' => 'INNER',
           'foreignKey' => 'user1',
           'propertyName' => 'user1'
        ]);

        $this->belongsTo('User2', [
           'className' => 'Users',
           'joinType' => 'INNER',
           'foreignKey' => 'user2',
           'propertyName' => 'user2'
        ]);
     }
}

ArticlesController.php:

class ArticlesController extends AppController {

    public function initialize() {
        parent::initialize();

    }

    public function index() {
        $this->paginate = ['contain' => ['User1', 'User2']];
        $articles = $this->paginate($this->Articles);

    }

    public function add() {
        $article = $this->Articles->newEntity();
        if ($this->request->is('post')) {
            $article = $this->Articles->patchEntity($article, $this->request->data);
            debug($article);
            debug($this->request->data); die;
        }
    }
}

Article.php

class Article extends Entity {
    protected $_accessible = [
        '*' => true
    ];
}

所有文章都显示在网页上。 (在ArticlesController上使用index())

问题是我在ArticlesController中调用add():

  

错误:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(dbnamearticles,CONSTRAINT fk_user1 FOREIGN KEY( user1)参考usersid))

有人可以解释我的错误吗?

提前致谢。

编辑: 这是输出数据:

[
    'title' => 'xxxxxx',
    'user1' => 'xxxxx',
    'user2' => 'xxxxxx'
]

object(App\Model\Entity\Article) {
    'title' => 'xxxxxxxx',
    '[new]' => true,
    '[accessible]' => [
        '*' => true
     ],
     '[dirty]' => [
         'title' => true
     ],
     '[original]' => [],
     '[virtual]' => [],
     '[errors]' => [],
     '[invalid]' => [],
     '[repository]' => 'Articles'
}

0 个答案:

没有答案