Php Laravel-ORM-调用未定义的方法
Php Laravel-ORM-调用未定义的方法,php,orm,laravel,Php,Orm,Laravel,app/models/Model.php: <?php class Model extends Eloquent { public function maker() { return $this->belongsTo('Maker', 'maker_id', 'id'); } } ?> 它给了我以下错误: BadMethodCallException Call to undefin
app/models/Model.php
:
<?php
class Model extends Eloquent {
public function maker()
{
return $this->belongsTo('Maker', 'maker_id', 'id');
}
}
?>
它给了我以下错误:
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
子句匹配的那些
但您需要的可能是(根据您的问题):
另一方面,它返回与where
类别匹配的模型,每个类别都有相关的制造者
注意:Model
类的名称空间,这样它就不会与illighted\Database\Eloquent\Model
(它将别名扩展为Eloquent)类似地“where”方法返回类型为Builder而不是ModelHmm的对象。关于如何解决这个问题,你有什么建议吗?你的模型太抽象了,不是吗?而不是模型
它应该是具体的表格,例如制造商<代码>生成器::where(“…”)->paginate(10)
请重新阅读问题。用户通过输入模型的标题执行搜索,搜索返回该模型的相应制作者。应该反转,首先制作对象,然后执行其中的:)为什么重复'models.title','LIKE',$query
?一个是模型.title
,另一个是制作者.title
// $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);
Model::with('maker')->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);