首页 > 解决方案 > 如何在范围内获得 Eloquent 关系

问题描述

$this 是命名空间App\Models\Product

protected $fillable = [ 'name', 'slug', 'company_id', 'original_price', 'discount_price', 'code', 'barcode', 'quantity', 'parent_id', 'position', 'status', 'short_description', 'long_description', 'approved', 'auto_approve' ];

代码:

public function childProducts()   
{ 
  return $this->hasMany(Product::class, 'parent_id', 'id'); 
}

我的范围

public function scopeActive($query) {
  return $query->where('status', 1); 
}

标签: laravelscopeproductrelation

解决方案


你可以这样做:

    public function scopeActive($query)
    {
        return $query->whereHas('childProducts', function($query) {
            $query->where('status', 1);
        });
    }

更新: 检查数量

    public function scopeActive($query)
    {
        return $query->where('quantity', '>', 0)->whereHas('childProducts', function($query) {
            $query->where('status', 1)->where('quantity', '>', 0);
        });
    }

推荐阅读