Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Added orderPivotBy for BelongsToMany relation #35455

Merged
merged 1 commit into from Dec 3, 2020

Conversation

smujaddid
Copy link
Contributor

This PR will allow us to directly order the query results of BelongsToMany relation such as:

class Tag extends Model
{
    public $table = 'tags';
}

class Post extends Model
{
    public $table = 'posts';

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_id')
            ->using(PostTagPivot::class)
            ->withTimestamps()
            ->withPivot('flag');
    }
}

class PostTagPivot extends Pivot
{
    protected $table = 'posts_tags';
}

// Somewhere in a controller
public function getPostTags($id)
{
    return Post::findOrFail($id)->tags()->orderPivotBy('flag', 'desc')->get();
}

Using orderPivotBy will allow us to not having to append the Tag class table name explicitly in case the flag attribute exists in both Tag and PostTagPivot. The results will be ordered based on flag value.

Note: I will also make a PR for [7.x] branch

@taylorotwell taylorotwell merged commit 400274e into laravel:8.x Dec 3, 2020
@smujaddid smujaddid deleted the 8.x-BelongsToMany-orderPivotBy branch December 30, 2020 07:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants