CakePHP 3.0保存belongsToMany不保存

时间:2015-02-24 17:35:12

标签: php cakephp model-view-controller model cakephp-3.0

我在Cake 3.0中保存关联数据时遇到问题。我有一个用户模型,用户可以是许多不同的音乐家。我有一个连接表users_musicians。

class UsersTable extends Table {

    public function initialize(array $config) {
        $this->addBehavior('Timestamp');

        $this->belongsToMany('Musicians', [
            'joinTable' => 'users_musicians',
        ]);

        $this->belongsTo('Counties', [
            'foreignKey' => 'county_id',
            'joinType' => 'INNER',
        ]);
    }

我发布了一个新用户,并试图在users_musicians表中保存一个音乐家类型,使用发布的musician_id并使用保存的新用户的user_id。

public function add() {
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        $newData = [
            'users_musicians' => [
                ['musician_id' => 10],
            ]
        ];
        $this->Users->patchEntity($user, $newData);

        echo '<br><br><pre>' . print_r($user, true) . '</pre>';
        //die();
        if ($this->Users->save($user)) {
            $this->Flash->success(__('Your details have been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to add your details.'));
    }
    $this->set('user', $user);
}

&#34; users_musicians&#34;的表结构是: id - int,AI,PK, user_id - int, musician_id - int, 创建 - 日期时间, 更新 - 日期时间

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在CakePHP for belongsToMany关联中,表名应按字母顺序排列,因此,将“users_musicians”表名更改为“musicians_users”并尝试使用。