I have 3 tables:
They are both many to many relationships with a pivot.
I need to query this to get all articles that have an array of tags:
Article::with('tags')->whereIn('id', $tagIdArray)->get();
The problem with the above is that it's returning articles that have the id of $tagIdArray. How can I constraint the results so that I use the whereIn on the tags relationship?
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
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.
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
You've got the right idea, but a little off the ball. Using the with('tags')
functions just pulls your Articles out with the related Tags, queries chained after the with()
function still apply to the Articles model.
To query a relation you can do the following
$tagIdArray = [1, 3, 5, 7, 9];
$articles = Article::whereHas('tags', function($query) use ($tagIdArray) {
/**
* Now querying the Tags relation. So anything in this closure will query the Tags
* relation, but outside of the closure, you're back to querying the Articles.
*/
$query->whereIn('id', $tagIdArray);
})->get();
Heres the Laravel docs on querying relations http://laravel.com/docs/4.2/eloquent#querying-relations
This is how I pull products by filtering data at the Model's Relationship level.
$youMayAlsoLike = Category::whereHas('product', function($query)
{
$query->whereIn('category_slug', ['gift-sets','multi-shade-sticks','eye pencil']);
})
->inRandomOrder()
->take(10)
->get();
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