2

我想知道如何从 3 个表创建关系。

这是我的模型结构:

用户模型

class User extends Eloquent { 
    public function Posts(){
        return $this->hasMany('Post');
    } 
    public function comments(){
        return $this->hasMany('comment');
    }
}


class Post extends Eloquent { 
    public function comments() {
        return $this->hasMany('Comments');
    } 
    public function user(){
        return $this->belongsTo('user');
    }    
}

class Comments extends Eloquent {  
    public function user(){
        return $this->belongsTo('user');
    }
    public function Post(){
        return $this->belongsTo('Post');
    } 
}

用户可以有很多帖子,每个帖子都有很多来自用户的评论。

我试图从发布评论的用户那里获取所有评论

$comments = Post::find(1)->comments()->get();
foreach ($comments as $comment) {
    // here my code now to get the user
    $comment->user()->get()
}

结果:

[
       {
        id: "1",
        post_id: "1",
        user_id: "1", 
        reply_text: "Testing", 
       },...
]

我认为它根本没有效率。

我怎样才能使它更简单,例如:

[
     {
        id: "1",
        post_id: "1",
        user_id: "1", 
        reply_text: "Testing", 
        user_post: {
            id: 1,
            name: "Edi vianika",
            profil_img: "l.jpg"
        }
    }
]
4

1 回答 1

0

Phill 的评论正确回答了这个问题,正如他所说,您应该使用Eager Loading

$post = Post::with('comments', 'comments.user')->find(1);

然后你可以像这样简单地迭代:

foreach ($post->comments as $comment) {
    echo $comment->user->name . ' said: ' . $comment->title;
}

只是为了清楚起见,我建议您将您的$comment->user关系命名为author,打字感觉很自然$comment->author->name。你可以这样做:

class Comments extends Eloquent {

    public function author()
    {
        return $this->belongsTo('user', 'user_id');
    }
}

// Remember to change eager loading to 'comments.author'
于 2013-06-07T01:58:24.763 回答