Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - condition on belongsTo relation

I use Laravel 5.6, I have 3 Models :

  • Area
  • Store
  • Merchant

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');
}
like image 508
Vincent Decaux Avatar asked Sep 16 '25 16:09

Vincent Decaux


1 Answers

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

public function merchant()
{
    return $this->belongsTo('Beproxy\App\Models\Merchant')
    ->where('state','1');
}
like image 152
Sachin Kumar Avatar answered Sep 18 '25 04:09

Sachin Kumar