Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WhereIn and relationships

I have 3 tables:

  • articles
  • tags
  • article_tag

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?

like image 961
panthro Avatar asked Mar 11 '15 16:03

panthro


People also ask

What is polymorphic relation in laravel?

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.

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.

What is eager loading in laravel?

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.

Does laravel have function?

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.


2 Answers

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

like image 198
Wader Avatar answered Sep 17 '22 19:09

Wader


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();
like image 22
hackernewbie Avatar answered Sep 19 '22 19:09

hackernewbie