php - CakePHP 3.0保存belongsToMany不保存

标签 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',
        ]);
    }

我正在通过一个新用户发布消息,并尝试使用发布的音乐家 ID 和保存的新用户的 user_id 在 users_musicians 表中保存单个音乐家类型。

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

“users_musicians”的表结构是: id - int,AI,PK, user_id - 整数, 音乐家_id - int, 创建 - 日期时间, 更新 - 日期时间

有什么建议吗?

最佳答案

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

关于php - CakePHP 3.0保存belongsToMany不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702512/

相关文章:

cakephp - nginx 正在从一个虚拟主机重定向到另一个

CakePHP 登录重定向到请求的 URL

asp.net-mvc - 使用默认模型 Binder 映射集合的约定是什么?

php - 如何使用 PHP 验证 Azure 广告 b2c token ?

php - 避免在为 WooCommerce 可变产品选择变体时更改图像

php - CakePHP 将数据传递给元素

c# - jstree下载

php - Heredoc:常用的 'EOT'究竟是什么意思?

php - 将数据插入到不同的表中

java - 从 spring Controller 下载文件 NotSerializedException