mardi 27 décembre 2016

CakePHP 3: save new entity (Error: Integrity constraint violation)

I make a new cakephp app but I have an error for several days.

This is the database structure:

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
    ];
}

All the articles are displayed on the web page. (with index() on the ArticlesController)

The problem is when I call add() in the ArticlesController:

Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (dbname.articles, CONSTRAINT fk_user1 FOREIGN KEY (user1) REFERENCES users (id))

Can someone explain me the error?

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire