mending3
mending3

Reputation: 712

Cannot seed from pivot table

ContactGroup::all()->each(function ($contactGroup) {
    $contactGroup->manyMessage()->save(factory(MessageMod::class, 10)->create());
});

I want to seed from populated pivot table (contact_group table with model named ContactGroup) to child table (messages table with model named MessageMod) but got Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails.

it logs:

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)

while it should have been:

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)

notice the latter there is contact_group_id field in the Insert SQL statement. If I run the latter manually on SQL console, it works. but the first one fails in terminal as well as SQL console

ContactGroup Model:

class ContactGroup extends Model
{
    protected $table = "contact_group";
    protected $guarded = [];

    public function manyMessage()
    {
        return $this->hasMany(MessageMod::class, 'contact_group_id');
    }
}

how do I fix this?

Upvotes: 0

Views: 36

Answers (1)

mending3
mending3

Reputation: 712

Solved by myself

I must add nullable to the migration.

Upvotes: 0

Related Questions