在where子句中指定表时的Eloquent错误

时间:2016-08-17 20:58:45

标签: php laravel eloquent

我有这个问题:

$query = Product::query();

$query->join('models AS m', 'products.model_id', '=', 'm.id');

if ($request->has('q')) {
    $terms = explode(' ', $request->get('q'));
    $query->orWhereHas('products.name', function($q) use ($terms) { $q->whereIn('name', $terms); });
}

它正在返回

Call to undefined method Illuminate\Database\Query\Builder::products()

如果我将products.category更改为其他任何内容,则错误会更改为新值,例如:

$query->orWhereHas('s.name', function($q) use ($terms) { $q->whereIn('name', $terms); });

将输出

Call to undefined method Illuminate\Database\Query\Builder::s()

我需要指定该类别属于名称,因为如果我不这样做,则返回不明确的字段存在。

我加入模型表的原因是因为我需要从模型

中选择一个字段
$query->get(['products.id', 'products.name', 'products.front_image', 'products.back_image', 'products.slug', 'm.slug as model_slug'])

如何在没有出现此错误的情况下在where子句中指定表?

1 个答案:

答案 0 :(得分:0)

whereHas方法用于查询关系;第一个参数应与模型中关系方法的名称相对应。在您的情况下,QueryBuilder尝试在Product模型上调用方法products()

如果您希望按名称查询记录,可以使用where()方法。