sharf
sharf

Reputation: 2143

Yii2 unlink records via junction table

I have two models; User and Raffle. I also have a junction table with just an id, a user_id, and a raffle_id.

I then get the Raffles from the User model like this:

public function getRaffles()
{
    return $this->hasMany(Raffle::class, ['id' => 'raffle_id'])
        ->viaTable('raffle_user', ['user_id' => 'id']);
}

And from the Raffles model like this:

public function getUsers()
{
    return $this->hasMany(User::class, ['id' => 'user_id'])
        ->viaTable('raffle_user', ['raffle_id' => 'id']);
}

This works, and I can successfully call $user->link('raffles', $raffle); etc.

However, when I try to unlink a record like $user->unlink('raffles', $raffle); I get the error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'raffle_id' cannot be null

Am I doing something wrong, or do I have something misconfigured?

Upvotes: 2

Views: 464

Answers (1)

Jiri Semmler
Jiri Semmler

Reputation: 421

The https://www.yiiframework.com/doc/guide/2.0/en/db-active-record says following

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.

So don't you have your column raffle_id defined as NOT NULL ? It would explain the situation.

You should pass true as third attribute or set off the NOT NULL settings on the column.

Btw, it should use the same relation. Why do you have there raffles when link and raffle when unlink?

Upvotes: 4

Related Questions