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

[7.x] Added orderPivotBy for BelongsToMany relation #35456

Closed

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: This is a backported #35455

Do I need to make a PR for [6.x] branch?

@driesvints
Copy link
Member

7.x is closed for new features sorry.

@driesvints driesvints closed this Dec 2, 2020
@smujaddid smujaddid deleted the 7.x-BelongsToMany-orderPivotBy branch December 30, 2020 07:34
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