当我尝试将数据保存到中间表时,我面临多对多关系的问题。基本上,一个客户有很多观察,我有tbl_cients
,clients_hasmany_observations
和tbl_clients_observations
。
迁移的外键:
Schema::connection('dev')->table('clients_hasMany_observations', function (Blueprint $table) {
$table->foreign('client_id')->references('client_id')->on('tbl_clients');
$table->foreign('observation_id')->references('observation_id')->on('tbl_clients_observations');
});
客户模型:
/**
* The observations that belong to the client.
*/
public function observations()
{
return $this->belongsToMany('App\ClientsObservations', 'clients_hasmany_observations', 'client_id', 'observation_id')->withTimestamps();
}
观察模型:
/**
* The observations that belong to the client.
*/
public function clients()
{
return $this->belongsToMany('App\Clients', 'clients_hasmany_observations', 'client_id', 'observation_id')->withTimestamps();
}
考虑到这一点,如果我尝试添加新客户端并附加虚拟观察值,则会出现错误:
SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(
helderne_dev
。clients_hasmany_observations
,CONSTRAINTclients_hasmany_observations_observation_id_foreign
外键(observation_id
),引用tbl_clients_observations
(observati) (SQL: insert into
clients_hasmany_observations(
client_id,
created_at,
observation_id,
updated_at`)值(4,2020-04-15 11:05:09,50,2020-04-15 11:05:09) )```
我真的不明白为什么,因为我添加了密钥。任何帮助将不胜感激!
编辑#1在控制器中,我正在编写:
$new_client = Clients::create($request->all());
$new_client->observations()->attach([50]);
dd($new_client);
50将是tbl_clients_observations中观测值的可能ID。
attach方法不接受数组(与类似的sync方法不同)。请参阅the documentation以供参考。
尝试以下操作:
$new_client->observations()->attach(50);
在将数据保存到表之前禁用外键检查
DB::statement('SET FOREIGN_KEY_CHECKS=0');
然后重新启用它
DB::statement('SET FOREIGN_KEY_CHECKS=1');
这将解决问题