Yii2 通过联结取消链接记录 table
Yii2 unlink records via junction table
我有两个模型;用户和抽奖。我也有一个连接点 table,只有一个 id
、一个 user_id
和一个 raffle_id
。
然后我像这样从用户模型中获取莱佛士:
public function getRaffles()
{
return $this->hasMany(Raffle::class, ['id' => 'raffle_id'])
->viaTable('raffle_user', ['user_id' => 'id']);
}
而莱佛士的模式是这样的:
public function getUsers()
{
return $this->hasMany(User::class, ['id' => 'user_id'])
->viaTable('raffle_user', ['raffle_id' => 'id']);
}
这有效,我可以成功调用 $user->link('raffles', $raffle);
等
但是,当我尝试取消链接像 $user->unlink('raffles', $raffle);
这样的记录时,我收到错误消息:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'raffle_id' cannot be null
是我做错了什么,还是配置有误?
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record 表示如下
By default, the unlink() method will set the foreign key value(s) that
specify the existing relationship to be null. You may, however, choose
to delete the table row that contains the foreign key value by passing
the $delete parameter as true to the method.
所以您没有将列 raffle_id
定义为 NOT NULL 吗?它会解释情况。
您应该将 true
作为第三个属性传递,或者在列上设置 NOT NULL
。
顺便说一句,它应该使用相同的关系。为什么 link
时有 raffles
而 unlink
时有 raffle
?
我有两个模型;用户和抽奖。我也有一个连接点 table,只有一个 id
、一个 user_id
和一个 raffle_id
。
然后我像这样从用户模型中获取莱佛士:
public function getRaffles()
{
return $this->hasMany(Raffle::class, ['id' => 'raffle_id'])
->viaTable('raffle_user', ['user_id' => 'id']);
}
而莱佛士的模式是这样的:
public function getUsers()
{
return $this->hasMany(User::class, ['id' => 'user_id'])
->viaTable('raffle_user', ['raffle_id' => 'id']);
}
这有效,我可以成功调用 $user->link('raffles', $raffle);
等
但是,当我尝试取消链接像 $user->unlink('raffles', $raffle);
这样的记录时,我收到错误消息:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'raffle_id' cannot be null
是我做错了什么,还是配置有误?
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record 表示如下
By default, the unlink() method will set the foreign key value(s) that specify the existing relationship to be null. You may, however, choose to delete the table row that contains the foreign key value by passing the $delete parameter as true to the method.
所以您没有将列 raffle_id
定义为 NOT NULL 吗?它会解释情况。
您应该将 true
作为第三个属性传递,或者在列上设置 NOT NULL
。
顺便说一句,它应该使用相同的关系。为什么 link
时有 raffles
而 unlink
时有 raffle
?