app/models/Model.php
:
<?php
class Model extends Eloquent {
public function maker()
{
return $this->belongsTo('Maker', 'maker_id', 'id');
}
}
?>
我想进行搜索。用户输入模型的名称,搜索应返回该模型的制造商(每个模型属于某个制造商(。以下代码不起作用:
$result = Model::where('title', 'LIKE', '%test%')->maker()->paginate(10);
它给了我以下错误:
BadMethodCallException
Call to undefined method Illuminate'Database'Query'Builder::maker()
有什么想法吗?
我已经解决了自己的问题。
$result = Model::where('models.title', 'LIKE', $query)
->leftJoin('makers', 'models.maker_id', '=', 'makers.id')
->orWhere('makers.title', 'LIKE', $query)
->groupBy('makers.title')
->paginate(10);
根据您的解决方案:
// $search is the keyword to find
Model::with(['maker' => function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%"); // where on makers table
}])->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
这将返回与where
子句匹配的Model
s,以及相关的Maker
s,但也只返回那些与where
子句匹配的。
但你需要的可能是这个(根据你的问题(:
Model::with('maker')->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
另一方面,返回与where
类相匹配的Model
,每个都具有相关的Maker
注意:Model
类的命名空间,这样它就不会与Illuminate'Database'Eloquent'Model
(它扩展为Eloquent(冲突