如何在 laravel 范围内使用模型函数?

how to use a model function in scope in laravel?

我有两个table
1- 产品
2- 折扣
我想 select 所有打折产品,但有一个问题,在折扣 table 中没有 product_id,有产品 ID 数组,如:["1","4" "23"] 表示此折扣适用于 id 为 1 或 4 或 23 的产品。
我已经在我的产品模型中创建了一个函数来定义产品是否有折扣并像这样使用它:
$product->hasDiscount(); //returns 1 or 0
我到底需要什么?
我需要一个如下所示的产品模型范围,以便在我的 select 查询中使用以获取所有打折产品:

public function scopeDiscounted($query)
{
return $query->where($this->hasDiscount() , '=' , 1); 
// I know this code is wrong, I just want to explain the needed code result
}

让我们从规范化您的数据开始,创建以下 table 并在迁移中循环。

public function up()
{
    Schema::create('discount_product', function (Blueprint $table) {
        $table->unsignedInteger('discount_id');
        $table->unsignedInteger('product_id');

        // add foreign keys if you like
    });

    Discount::all()->each(function (Discount $discount) {
        $productIds = json_encode($discount->productIds);
    
        foreach ($productIds as $productId) {
            $discount->saveMany(Product::whereIn('id', $productIds)->get());
        }
    });
}

要使此迁移工作,您必须在 运行 迁移之前创建关系。我懒得在迁移中使用模型,最好的方法是使用 DB facade。

class Discount {
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}


class Product {
    public function discounts()
    {
        return $this->belongsToMany(Discount::class);
    }
}

现在你应该可以得到所有打折的产品了,你可以把它放在你的范围内。

$discountedProducts = Product::whereHas('discounts', function ($query) {
    $query->where('active', true);
    $query->whereDate('expire_at', '>=', now())
})->get();