代码之家  ›  专栏  ›  技术社区  ›  Vincent Decaux

关于belongsTo关系的条件

  •  2
  • Vincent Decaux  · 技术社区  · 7 年前

    我使用的是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 function storesWithProducts()
    {
        return $this->hasMany('App\Models\Store')->has('products');
    }
    

    但我不知道如何使用条件 属于 ,我试了试 地区 ,但它会加载所有内容:

    public function storesWithMerchantActive()
    {
        return $this->hasMany('App\Models\Store')
            ->with(['merchant' => function($query) {
                $query->where('state', '=', 1);
            }])
            ->has('products');
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   eResourcesInc    7 年前

    你不必使用其他关系。您可以使用商店whereHas上的商品,并检查活跃的商户,如下所示:

    public function storesWithMerchantActive()
    {
        return $this->storesWithProducts->whereHas('merchant', function ($query) {
            $query->where('state', 1);
        })->get();
    }
    
        2
  •  3
  •   Sachin Kumar    7 年前

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