首页 > 解决方案 > Get all products except that already had discount?

问题描述

I have these two tables:

products table:

name - price - quantity - etc

discounts table:

type('percentage','numeric') - value - cancel - expired_at

Polymorphic relations: discountables table:

discount_id - discountable_id - discountable_type

there is Many To Many (Polymorphic) between them. So I need to get all products except that already had discount + the products that had discount but it's over with expired_at

Product model:

public function discounts()
{
    return $this->morphToMany('App\Models\Discount', 'discountable');
}

Discount Model:

public function products()
{
    return $this->morphedByMany('App\Models\Product', 'discountable')->withTimestamps();
}

My wrong shut!:

public function index()
{
    $products = Product::with('discounts');

    return view('cp.discounts.index', compact('products'));
}

标签: phplaravel

解决方案


You can use doesntHave method,

The follow query will retrieve all products that don't have any discounts.

Product::doesntHave('discounts')->get();

And if you want to get the products except it's over with expired_at + don't have any discounts, you can use whereDoesntHave to add condition in closure:

Product::whereDoesntHave('discounts', function($query) {
    $query->where('expired_at', '>', \Carbon\Carbon::now()->format('Y-m-d H:i:s'));
})->get();

推荐阅读