PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to get Eloquent relationship in scope

 May 09, 2022     laravel, product, relation, scope     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing