Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is relationship count condition in WhereHas Laravel

I am having a difficulty understanding the relationship count condition in WhereHas. The docs page does not have discussion about it but API page talks about it. Quote from API.

Builder|Builder whereHas(string $relation, Closure $callback, string $operator = '>=', int $count = 1)

Add a relationship count condition to the query with where clauses.

Example

A Resource Model has Many to Many relation to ResourceCategory

public function categories()
{
    return $this->belongsToMany('ResourceCategory', 'resource_category_mapping');
}

Relationship condition in Has

The relationship condition in Has is working as expected.

Resource::has('categories', '>', 1)->get()
//this return all resources which have more than one catgories

Relationship condition in WhereHas

The relationship condition in WhereHas is not working as expected. I am sure I have misunderstood it.

Resource::whereHas('categories', function ( $query){
            $query->whereIn('resource_category_id', [1, 2, 4]);
        }, '>', 1)->get()

The above code should return resources which whose categories belong to either of [1, 2, 4] and the resource has more than one categories. But it is not.

Question

Kindly explain the relationship condition in WhereHas, may be providing an example would be much helpful.

like image 413
hhsadiq Avatar asked Jul 25 '15 07:07

hhsadiq


People also ask

What is count in laravel?

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array: $wordCount = count($wordlist); If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method.

How does laravel count Hasmany relationships?

Step 1: Place this code inside your 'Post' model. Step 2: Place this code inside your 'PostController' controller. $posts= Post::all(); return view('home')->with('posts', $posts); Step 3: Then count comments for all posts using the below code.

How many types of relations are there in laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)


1 Answers

Normally, whereHas() checks if your model has at least one related model. You can set $count to some higher value to increase the count to Nand fetch only the models that have at least N related models.

In your case, calling

Resource::has('categories', '>', 2)->get();

will return only those Resources that have at least 2 related categories.

like image 143
jedrzej.kurylo Avatar answered Sep 24 '22 20:09

jedrzej.kurylo