【问题标题】:Get all products except that already had discount?获得除已经有折扣的所有产品吗?
【发布时间】:2020-02-10 07:06:04
【问题描述】:

我有这两张表:

产品表:

name - price - quantity - etc

折扣表:

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

多态关系:折扣表:

discount_id - discountable_id - discountable_type

它们之间有Many To Many (Polymorphic)。所以我需要得到除了已经有折扣的所有产品+有折扣但已经结束的产品expired_at

产品型号:

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

折扣模式:

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

我关错了!:

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

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

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你可以使用doesntHave方法,

    以下查询将检索所有没有任何折扣的产品。

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

    如果您想获得除expired_at 之外的产品 + 没有任何折扣,您可以使用whereDoesntHave 在关闭时添加条件:

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

    【讨论】:

    • 先生,我有一个有线问题!如何从文档中找到我需要的东西?
    • @Jamal 喜欢这个问题,它是关于关系的,所以你需要找到关系部分。
    • 先生,我更新了我的问题!你能再看一遍吗!
    • @Jamal 已更新。您可以使用whereDoesntHave添加条件。
    • 它带来了整个产品!
    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多