使用Eloquent关系可以调用未定义的方法'

时间:2014-09-07 09:32:20

标签: laravel-4

在Laravel的文档中,有一个示例显示了如何链接模型之间的关系。

// one to many relationship
$comments = Post::find(1)->comments;

所以这就是你如何检索所有评论,对于id为1的帖子。

但为什么我不能使用与where链接的关系,我一直在

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

这是我的代码:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
                                ->classifieds()
                                ->where('is_approved', 'true')
                                ->get();

这是来自ClassifiedCategory模型的相关代码:

public function classifieds() {
 return $this->hasMany('Classified');
}

2 个答案:

答案 0 :(得分:1)

您可以尝试使用whereHas

$classifieds = Classified::where('is_approved', 'true')
                        ->whereHas('classifiedCategory', function($q) use($slug) {
                            $q->where('slug', 'like', $slug);
                        })
                        ->get();

假设您也定义了反比关系。

public function classifiedCategory() {
    return $this->belongsTo('Classified');
}

答案 1 :(得分:1)

可以使用

whereHas,但这就是为什么您的代码无法正常工作以及如何使其有效的原因:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
    // here you are trying to call relation before you fetched the model
    ->classifieds() 
    ->where('is_approved', 'true')
    ->get();

所以你需要:

$classifieds = ClassifiedCategory::where('slug', 'like', $slug)
    ->first() // fetch the category
    ->classifieds()  // now query the relation
    ->where('is_approved', 'true')
    ->get();