Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ public function newPivotQuery()
call_user_func_array([$query, 'whereIn'], $arguments);
}

foreach ($this->pivotWhereNulls as $arguments) {
call_user_func_array([$query, 'whereNull'], $arguments);
}

return $query->where($this->foreignPivotKey, $this->getParentKeyValue());
}

Expand Down
39 changes: 39 additions & 0 deletions tests/Integration/PivotTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,40 @@ public function testDetach()

$this->assertEquals(0, $first->second_models()->count());
}

public function testDetachRespectsWherePivotNull()
{
$first = $this->attachTwoModelsWithoutPivotClass();

$first->second_models_without_pivot_class()->wherePivotNull('extra')->detach();

$this->assertEquals(['Second m'], $first->second_models_without_pivot_class()->pluck('name')->all());
}

public function testUpdateExistingPivotRespectsWherePivotNull()
{
$first = $this->attachTwoModelsWithoutPivotClass();
$secondM = SecondModel::where('name', 'Second m')->first();

$updated = $first->second_models_without_pivot_class()->wherePivotNull('extra')
->updateExistingPivot($secondM, ['extra' => 'changed']);

$this->assertEquals(0, $updated);
$this->assertEquals(1, DB::table('first_model_second_model')->where('extra', 'm')->count());
}

private function attachTwoModelsWithoutPivotClass(): FirstModel
{
$first = (new FirstModel())->create(['id' => (string) Uuid::uuid1()->getHex(), 'name' => 'First']);
$secondNull = (new SecondModel())->create(['id' => (string) Uuid::uuid1()->getHex(), 'name' => 'Second null']);
$secondM = (new SecondModel())->create(['id' => (string) Uuid::uuid1()->getHex(), 'name' => 'Second m']);

$first->second_models_without_pivot_class()->attach($secondNull, ['extra' => null]);
$first->second_models_without_pivot_class()->attach($secondM, ['extra' => 'm']);
$this->assertEquals(2, $first->second_models_without_pivot_class()->count());

return $first;
}
}

class FirstModel extends Model
Expand Down Expand Up @@ -128,6 +162,11 @@ public function second_models()
SecondModel::class
)->using(FirstModelSecondModelPivot::class);
}

public function second_models_without_pivot_class()
{
return $this->belongsToMany(SecondModel::class);
}
}

class SecondModel extends Model
Expand Down
Loading