简体   繁体   English

如何建立多对多关系3 laravel模型4

[英]How to create relation many to many 3 Model laravel 4

I wonder how to create relation from 3 tables. 我想知道如何从3个表创建关系。

Here is my model structure: 这是我的模型结构:

User Model 用户模型

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');
    } 
}

User can have many post, and each post has many comments from user. 用户可以有很多帖子,每个帖子都有很多用户评论。

I tried to grab all comments from post with user who posted the comment 我试图与发布评论的用户从发布中获取所有评论

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

The result: 结果:

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

I think it's not efficient at all. 我认为这根本没有效率。

How can I make this more simple like: 我如何使它更简单,例如:

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

This is correctly answered on comments by Phill, and as he says, you should user Eager Loading . Phill的评论正确回答了这一问题,正如他所说,您应该使用Eager Loading

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

Then you can simply iterate like this: 然后,您可以像这样简单地进行迭代:

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

Just for clarity tho, I would suggest you to name your $comment->user relationship to author instead, it feels natural to type $comment->author->name . 为了清楚起见,我建议您将$comment->user关系命名为author ,键入$comment->author->name感觉很自然。 You could do so as: 您可以这样做:

class Comments extends Eloquent {

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

// Remember to change eager loading to 'comments.author'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM