2015-12-10 46 views
0

我有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> 

你有什麼傢伙的意見嗎?這是正確的方法嗎?或者有什麼不同,你推薦?

回答

0

解決您的第一個問題,我在做什麼的觀點是,我通過用戶已通過執行類似創建你可以使用Eager Loading的所有帖子循環 - 但是,這將要求您訪問嵌套元件(一個或多個)。這個查詢檢索用戶和他的所有職務,包括評論者:

$user = User::with('post.commenters')->where('id', $userId)->firstOrFail(); 

這樣你就可以訪問用戶帖子$user->post的數組。然後訪問它的評論者,你可以指定數組索引(或使用foreach loop).IE: - 經常或視圖(我

//this is array access, accessing first post 
$user->post[0]; 
//this iterate all post using foreach 
foreach($user->post as $posts){ 
    $post-> //do something with current post? 
} 

至於你的第二個麻煩,計數,它可以在數據庫中查詢完成做到這一點,因爲它相當簡單,可讀和少查詢)。

//this prints all posts number of commenters - in blade 
@foreach($user->post as $posts) 
    @foreach($posts->commenter as $commenter) 
    {{ count($commenter) }} 
    @endforeach 
@endforeach 

編輯: 看起來像我錯過仔細閱讀你的模型,它..不能做

return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'username'); 

應該

return $this->hasManyThrough('App\User', 'App\Comment', 'user_id', 'id'); 
實際上

你使用user_id而不是其用戶名作爲註釋中的外鍵。

+0

嗨tezla,我期待計算已評論的用戶數量。不是評論的數量。 –

+0

啊mybad,你可以通過急切的加載獲取用戶 - 我會編輯我的答案。 –

+0

如果你想檢索後評論者,看着你的模型關係 - 可以通過它來完成,但是,它不會檢索實際的評論。 –