Laravel-ORM-对未定义方法的调用


Laravel - ORM - call to undefined method

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子句匹配的Models,以及相关的Makers,但也只返回那些与where子句匹配的。

但你需要的可能是这个(根据你的问题(:

Model::with('maker')->where('title', 'like', "%{$search}%") // where on models table
    ->paginate(10);

另一方面,返回与where类相匹配的Model,每个都具有相关的Maker

注意:Model类的命名空间,这样它就不会与Illuminate'Database'Eloquent'Model(它扩展为Eloquent(冲突