laravel eloquent,只检查onetomany关系中的第一项

laravel eloquent, check only first item in onetomany relationship

我有 2 个模型:

价格多的产品型号:

public function prices()
{
    return $this->hasMany(Price::class)->orderBy('price', 'DESC');
}

属于产品的价格模型:

public function product()
{
    return $this->belongsTo(Product::class);
}

还有一些其他的关系。我有这样的查询:

    $query = Product::query();
    $query->where('brandId', $brand->id);
    $query->where('termId', $termId);
    $query->when($productType, function ($q) use ($productType){
        $q->with('productAttributes')->whereHas('productAttributes', function($query) use ($productType){
            $query->where(['attributeId'=> 5, 'attributeDataId'=>$productType]);
        });
    });

我也想查询商品价格

主要问题是我只想检查第一个价格,看看它是否小于给定的数字。

此查询检查所有价格(这不是我想要的):

    $query->when($maxPrice, function ($q) use ($maxPrice){
        $q->with('prices')->whereHas('prices', function($query) use ($maxPrice){
            $query->where('price', '<=', $maxPrice);
        });
    });

您可以为此使用 subquery where clause

->where(function ($query) {
    $query->select('price')
        ->from('prices')
        ->whereColumn('products.id', 'prices.product_id')
        ->orderByDesc('price')
        ->limit(1);
}, '<=', $maxPrice)

您的查询类似于:

$query = Product::query()
    ->where('brandId', $brand->id)
    ->where('termId', $termId)
    ->when($productType, function ($q) use ($productType) {
        $q->with('productAttributes')
            ->whereHas('productAttributes', function ($query) use ($productType) {
                $query->where(['attributeId' => 5, 'attributeDataId' => $productType]);
            });
    })
    ->when($maxPrice, function ($q) use ($maxPrice) {
        $q->with('prices')->where(function ($query) {
            $query->select('price')
                ->from('prices')
                ->whereColumn('products.id', 'prices.product_id')
                ->orderByDesc('price')
                ->limit(1);
        }, '<=', $maxPrice);
    });