Laravel 关于belongsTo关系的条件
我使用Laravel 5.6,我有3种型号:Laravel 关于belongsTo关系的条件,laravel,eloquent,Laravel,Eloquent,我使用Laravel 5.6,我有3种型号: 区域 贮藏 商人 区域有许多商店: public function stores() { return $this->hasMany('Beproxy\App\Models\Store'); } public function merchant() { return $this->belongsTo('Beproxy\App\Models\Merchant'); } 商店属于一个商户: public functio
- 区域
- 贮藏
- 商人
public function stores()
{
return $this->hasMany('Beproxy\App\Models\Store');
}
public function merchant()
{
return $this->belongsTo('Beproxy\App\Models\Merchant');
}
商店属于一个商户:
public function stores()
{
return $this->hasMany('Beproxy\App\Models\Store');
}
public function merchant()
{
return $this->belongsTo('Beproxy\App\Models\Merchant');
}
在我的商户中,我有一个提示来定义该商户是否处于活动状态(状态)
我是否可以在我的区域模型中编写一个新函数,以获取属于活跃的商户的所有门店
有很多关系,我可以使用:
public function storesWithProducts()
{
return $this->hasMany('App\Models\Store')->has('products');
}
但我找不到如何使用belongsTo的条件,我在我的区域中尝试了,但它加载了所有内容:
public function storesWithMerchantActive()
{
return $this->hasMany('App\Models\Store')
->with(['merchant' => function($query) {
$query->where('state', '=', 1);
}])
->has('products');
}
我想你只需要更新这个函数就可以了
public function merchant()
{
return $this->belongsTo('Beproxy\App\Models\Merchant')
->where('state','1');
}
您不必为此使用其他关系。您可以在storesWithProducts上使用whereHas,并检查是否有活跃的商户,如下所示:
public function storesWithMerchantActive()
{
return $this->storesWithProducts->whereHas('merchant', function ($query) {
$query->where('state', 1);
})->get();
}
不错的一个,我想
和也会这样做。