Laravel-属于归属关系的条件

时间:2018-11-12 13:45:49

标签: 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');
}

在我的商人中,我有一个tinyInt来定义商人是否处于活动状态(状态

我可以在我的区域模型中编写新功能来获取属于活动商人的所有商店吗?

有了 hasMany 关系,我可以使用:

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

但是我找不到如何为 belongsTo 使用条件,我在 Area 区域中尝试过,但是它可以加载所有内容:

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

2 个答案:

答案 0 :(得分:1)

我认为您只需要更新此功能可能会有所帮助。

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

答案 1 :(得分:1)

您不必为此使用其他关系。您可以利用storesWithProducts上的wheres并检查活跃的商人,如下所示:

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