diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index f2904972cc3f..585deb1aa61d 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -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. * diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 5780b61e7020..f560df2e8118 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -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