我有3個數據庫表。這是正確的Laravel 5模型關係嗎?
users
id - integer
username - string
post
id - integer
user_id - integer
topic - string
comments
id - integer
user_id - integer
post_id - integer
我在視圖中做什麼,我通過一個用戶通過做一些像創建
Post::where('user_id', Auth::user()->id)->get();
在每篇文章的所有帖子循環,其他用戶可以對它們發表評論。我希望在帖子中顯示一條記錄,它可以唯一記錄有多少用戶對該帖子發表了評論。我認爲創建一個hasManyThrough關係可以在這裏工作,但我一直在爲用戶獲得「0」數。
用戶模型:
class User extends Model {
public function post()
{
return $this->hasMany('App\Post')
}
public function comment()
{
return $this->hasMany('App\Comment', 'user_id')
}
}
郵政型號:
class Post extends Model {
public function user()
{
return $this->belongsTo('App\User')
}
public function comment()
{
return $this->hasMany('App\Comment')
}
// I thought this method below would return the users who had commented on the post
public function commenters()
{
return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'username');
}
}
評論模型:
class Comment extends Model {
pubic function user()
{
return $this->belongsTo('App\User')
}
public function post()
{
return $this->belongsTo('App\Post')
}
}
所以,最終的結果應該是這樣的即時猜測?
查看:
<span>{{ $model->modelmethod->count() }}</span>
你有什麼傢伙的意見嗎?這是正確的方法嗎?或者有什麼不同,你推薦?
嗨tezla,我期待計算已評論的用戶數量。不是評論的數量。 –
啊mybad,你可以通過急切的加載獲取用戶 - 我會編輯我的答案。 –
如果你想檢索後評論者,看着你的模型關係 - 可以通過它來完成,但是,它不會檢索實際的評論。 –