2014-03-07 255 views
0

如果我想找到帖子有評論,這就像雄辯在Laravel

Post::with('comments')->has('comments'); 

就我而言,我有一個意見表,只爲每個評論的一份答覆,因此,結構

意見表

id 
name 
comment_id 

評價模型

public function reply() { 
    return $this->hasOne('comment', 'comment_id'); 
} 

如果我想找個話題

Comment::whereNull('comment_id'); 

但是,如果我想找出評論已回覆

Comment::whereNull('comment_id')->has('reply'); 

這將是空的,如何找出註解的,而不是有通過此結構回覆

回答

0

您錯過了您的關係中的return

public function reply() { 
    return $this->hasOne('Comment'); 
} 

你也可以找到你需要定義外鍵:

public function reply() { 
    return $this->hasOne('Comment', 'comment_id'); 
} 

這裏是供您參考文檔:http://laravel.com/docs/eloquent#one-to-one

編輯:

你會發現你需要使用hasMany而不是hasOne

public function reply() { 
    return $this->hasMany('Comment', 'comment_id'); 
} 
+0

對不起,這是錯字,我已經做了,但仍然無法使用 – Chan

+0

您可能需要嘗試帶有外鍵的'hasMany'。請參閱編輯。 –