Vincent Decaux
Vincent Decaux

Reputation: 10714

Laravel - condition on belongsTo relation

I use Laravel 5.6, I have 3 Models :

Area has many Stores :

public function stores()
{
    return $this->hasMany('Beproxy\App\Models\Store');
}

Store belongs to one Merchant :

public function merchant()
{
    return $this->belongsTo('Beproxy\App\Models\Merchant');
}

In my Merchant, I have one tinyInt to define if the Merchant is active or not (state)

Can I write a new function in my Area Model to get all Stores which belong to an active Merchant ?

With hasMany relation, I can use :

public function storesWithProducts()
{
    return $this->hasMany('App\Models\Store')->has('products');
}

But I don't find how to use a condition for belongsTo, I tried in my Area, but it loads everything :

public function storesWithMerchantActive()
{
    return $this->hasMany('App\Models\Store')
        ->with(['merchant' => function($query) {
            $query->where('state', '=', 1);
        }])
        ->has('products');
}

Upvotes: 4

Views: 17295

Answers (2)

eResourcesInc
eResourcesInc

Reputation: 1028

You don't have to use another relation for this. You could utilize whereHas on the storesWithProducts and check for a merchant that is active as shown below:

public function storesWithMerchantActive()
{
    return $this->storesWithProducts->whereHas('merchant', function ($query) {
        $query->where('state', 1);
    })->get();
}

Upvotes: 5

Sachin Kumar
Sachin Kumar

Reputation: 3240

I think you just need to update this function may help.

public function merchant()
{
    return $this->belongsTo('Beproxy\App\Models\Merchant')
    ->where('state','1');
}

Upvotes: 9

Related Questions