【发布时间】:2020-08-11 02:19:06
【问题描述】:
我有一个 Product 模型,它有很多 SalePrices(随着时间的推移而变化),存储在两个通过外键和雄辩关系链接的数据库表中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function sale_prices()
{
return $this->hasMany('App\SalePrices');
}
}
我要做的是根据传入的 Http 请求查询过滤产品,因此我在控制器中获得产品列表:
$products = Product::whereIn('type', $request->types)->where('active', 1);
然后,我检查最低价格或最高价格,并尝试进行相应的过滤:
if ($request->has('min_price')) {
$products->sale_prices()->where('price', '>=', $request->min_price);
}
if ($request->has('max_price')) {
$products->sale_prices()->where('price', '<=', $request->max_price);
}
$products = $products->get();
这不起作用,并给我这个错误:
Call to undefined method Illuminate\Database\Eloquent\Builder::sale_prices()
我知道 $products 变量现在是项目的集合,但我不确定如何在这些项目上应用我的过滤器。我可以遍历它们,但我将如何应用我正在寻找的 where 子句?
【问题讨论】: