[英]Laravel Eloquent hasMany relationship
嗨,我是 Laravel 的新手,目前正在使用 Laravel 4.2。 我正在嘗試創建一個應用程序,其中有用戶、帖子和評論表並具有以下模型
用戶模型
function posts() {
return $this->hasMany('Post');
}
function comments(){
return $this->hasMany('Comment');
}
后模型
function users() {
return $this->belongsTo('User');
}
function comments() {
return $this->hasMany('Comment');
}
評論模型
function posts(){
return $this->belongsTo('Post');
}
function users(){
return $this->belongsTo('User');
}
我想要達到的目標:
用戶的帖子和帖子的評論
eg:: User1 -> Post one -> comment for post one
到目前為止我做了什么:::
$user = User::find(1);
$post = $user->posts()->get();
我可以發帖,但我如何獲得對特定帖子的評論?
更新
感謝@Bogdan 的幫助,我能夠為用戶發布和評論。 但像往常一樣有另一個問題。
我得到了什么:
foreach($user->post AS $post) {
foreach ($post->comment AS $comment ) {
$comment->commentcontent; $user->uername;
}
}//first foreach
這就是我得到的
comment one by user1.
comment two by user1.
但實際上評論一是由 user1 創建的,評論二是由 user2 創建的。
提前謝謝你的幫助。 如果需要,可以發布完整的代碼。
當您使用$user->posts()->get()
檢索用戶的帖子時,將獲得一個Models
Collection
,您可以在其上使用find
來獲取所需的特定帖子。 然后,您可以按照檢索用戶帖子的方式檢索帖子的評論:
$user = User::find(1);
$post = $user->posts()->find($postId);
$comments = $post->comments;
如果要遍歷整個帖子集合,則可以執行此操作並單獨訪問每個帖子的評論,而無需過濾特定帖子:
foreach ($user->posts as $post)
{
$comments = $post->comments;
}
另外,為將來參考,將關系作為屬性訪問將返回Collection,而將方法作為關系訪問將返回查詢構建器實例。 因此$user->posts
與$user->posts()->get()
。
您想要獲得發表評論的用戶,因此請從評論對象獲得該用戶。
嘗試這個
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}
添加到
wiseodd<\/code>答案。
您可以急切加載
posts<\/code>以防止 N + 1 問題。
$user = User::with('posts.comments')->find($post_id);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.