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?
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With