Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a related model within a Laravel query scope

I have a query scope method that filters results on a Foo model by the author of the model. The complication is that the author is not directly related.

Foo belongs to Bar and Bar belongs to User. If Foo belonged to User, I could just do this:

public function scopeAuthorOnly($query, User $user)
{
    return $query->whereuser_id($user->id);
}

This obviously won't work as the Foo model has no user_id column and instead has a bar_id column. However I'm not sure how I can build the query in a way that would filter the user_id.

Any pointers?

like image 638
Russ Back Avatar asked Aug 29 '13 21:08

Russ Back


People also ask

What are query scopes in Laravel?

Scoping is one of the superpowers that eloquent grants to developers when querying a model. Scopes allow developers to add constraints to queries for a given model. Utilizing Eloquent's Scoping helps us to follow the DRY principles when writing queries for our models.

What is global scope in Laravel?

Global scopes allow you to add constraints to all queries for a given model. Laravel's own soft delete functionality utilizes global scopes to only retrieve “non-deleted” models from the database. In this article, we'll create our own global scope.

What is local scope in Laravel?

It is a querying method in Laravel in which we can create a specific scope or you could say it is a function in a Model file that can query data that is used redundantly all over the project, let me simplify it with an example.

What is relationship in Laravel?

Defining Relationships. Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.


1 Answers

Found a solution:

public function scopeAuthorOnly($query, User $user)
{
    $query
        ->join('bars', 'foos.bar_id', '=', 'bars.id')
        ->join('users', 'bars.user_id', '=', 'users.id')
        ->where('users.id', '=', $user->id);

    return $query;
}
like image 81
Russ Back Avatar answered Oct 20 '22 12:10

Russ Back