Skip to content

Commit

Permalink
[8.x] Added orderPivotBy for BelongsToMany relation
Browse files Browse the repository at this point in the history
  • Loading branch information
smujaddid committed Dec 2, 2020
1 parent 7618102 commit 400274e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Expand Up @@ -556,6 +556,18 @@ public function orWherePivotNotNull($column)
return $this->orWherePivotNull($column, true);
}

/**
* Add an "order by" clause for a pivot table column.
*
* @param string $column
* @param string $direction
* @return $this
*/
public function orderPivotBy($column, $direction = 'asc')
{
return $this->orderBy($this->qualifyPivotColumn($column), $direction);
}

/**
* Find a related model by its primary key or return new instance of the related model.
*
Expand Down
22 changes: 22 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Expand Up @@ -905,6 +905,28 @@ public function testPivotDoesntHavePrimaryKey()
$user->postsWithCustomPivot()->updateExistingPivot($post2->uuid, ['is_draft' => 0]);
$this->assertEquals(0, $user->postsWithCustomPivot()->first()->pivot->is_draft);
}

public function testOrderPivotByMethod()
{
$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()->orderPivotBy('flag', 'asc')->first();
$this->assertEquals($relationTag1->getAttributes(), $tag2->getAttributes());

$relationTag2 = $post->tagsWithCustomExtraPivot()->orderPivotBy('flag', 'desc')->first();
$this->assertEquals($relationTag2->getAttributes(), $tag3->getAttributes());
}
}

class User extends Model
Expand Down

0 comments on commit 400274e

Please sign in to comment.