Skip to content

Commit

Permalink
Adds Conditionable Trait to Relation (#37640)
Browse files Browse the repository at this point in the history
  • Loading branch information
nedwors authored Jun 11, 2021
1 parent e886360 commit e3adb1c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\Macroable;

Expand All @@ -18,7 +19,7 @@
*/
abstract class Relation
{
use ForwardsCalls, Macroable {
use Conditionable, ForwardsCalls, Macroable {
__call as macroCall;
}

Expand Down
28 changes: 28 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,34 @@ public function testOrderByPivotMethod()
$relationTag2 = $post->tagsWithCustomExtraPivot()->orderByPivot('flag', 'desc')->first();
$this->assertEquals($relationTag2->getAttributes(), $tag3->getAttributes());
}

public function testOrderByPivotIsConditionable()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()]);
$tag3 = Tag::create(['name' => Str::random()]);
$tag4 = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);

DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo3'],
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'foo1'],
['post_id' => $post->id, 'tag_id' => $tag3->id, 'flag' => 'foo4'],
['post_id' => $post->id, 'tag_id' => $tag4->id, 'flag' => 'foo2'],
]);

$relationTag1 = $post->tagsWithCustomExtraPivot()
->when(true, function ($query) {
$query->orderByPivot('flag', 'asc');
})->first();
$this->assertEquals($relationTag1->getAttributes(), $tag2->getAttributes());

$relationTag2 = $post->tagsWithCustomExtraPivot()
->unless(false, function ($query) {
$query->orderByPivot('flag', 'desc');
})->first();
$this->assertEquals($relationTag2->getAttributes(), $tag3->getAttributes());
}
}

class User extends Model
Expand Down

0 comments on commit e3adb1c

Please sign in to comment.