ContactGroup::all()->each(function ($contactGroup) {
$contactGroup->manyMessage()->save(factory(MessageMod::class, 10)->create());
});
我想从填充的数据透视表(模型名为ContactGroup的contact_group表)播种到子表(模型名为MessageMod的消息表),但得到
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails.
它记录:
insert into messages (content_text, level, sentiment_result, updated_at, created_at) values (Sunt tempore nihil suscipit et maiores ducimus. Unde tempora quo quo. Ipsum officia perspiciatis perspiciatis provident dolor qui odit., 0, 2, 2019-11-21 23:13:42, 2019-11-21 23:13:42)
应为:
insert into messages (content_text, level, sentiment_result, updated_at, created_at, contact_group_id) values (Sunt tempore nihil suscipit et maiores ducimus. Unde tempora quo quo. Ipsum officia perspiciatis perspiciatis provident dolor qui odit., 0, 2, 2019-11-21 23:13:42, 2019-11-21 23:13:42, 1)
请注意,后者在Insert SQL语句中有contact_group_id
字段。
如果我在SQL控制台上手动运行后者,那么它将起作用。但是第一个在终端以及SQL控制台上都失败了
ContactGroup模型:
class ContactGroup extends Model
{
protected $table = "contact_group";
protected $guarded = [];
public function manyMessage()
{
return $this->hasMany(MessageMod::class, 'contact_group_id');
}
}
我该如何解决?
答案 0 :(得分:1)
自己解决
我必须为迁移添加可空值。