Monday, May 9, 2022

[FIXED] How to get Eloquent relationship in scope

Issue

$this is namespace 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' ];

Code:

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

My scope

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

Solution

You can do it like:

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

Update: check quantity

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


Answered By - Mohsen Nazari
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.