使用Eloquent将两个查询合并为一个

时间:2017-10-18 05:58:43

标签: laravel laravel-5 eloquent laravel-eloquent

我有两个查询在3个表Users,Comments和Posts中显示信息。所以我做了这个功能:

public function show($id)
    {
        $posts = Post::with(['comments'])->findOrFail($id);
        $user = User::find($posts->user_id);

        echo "<h1>".$posts->title.'</h1>';
        echo "<h2>".$user->name.'</h2>';

        foreach ($posts->comments as $comment) {
            echo $comment->body.'<br>';
        }
    }

在这个函数上我使用两个变量$ posts和$ user,我可以使用eloquests命令合并这两个变量,比如Post :: with(['user','comments'])'?所以我可以使用$ posts变量并使用它像$ posts-&gt; users-&gt; name来访问用户名。

我正在尝试使用这种方式:

$posts = Post::with(['comments','users'])->findOrFail($id);

但是当我回显帖子时显示用户为空:

{"id":1,"user_id":1,"title":"Oleh id 1","body":"ini adalah content","created_at":"2017-10-18 03:25:54","updated_at":"2017-10-18 03:25:54","comments":[{"id":1,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:50","updated_at":"2017-10-18 03:43:50"},{"id":2,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:53","updated_at":"2017-10-18 03:43:53"},{"id":3,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:54","updated_at":"2017-10-18 03:43:54"}],"users":null}

如果您需要,这是我的模型。我的帖子模型:

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function users(){
        return $this->belongsTo('App\User');
    }
}

我的评论模型

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

3 个答案:

答案 0 :(得分:0)

我猜是你想要用户的所有帖子的列表。如果定义了关系,请尝试使用join

$posts   =   DB::table('posts')
             ->join('users', 'users.id', '=', 'posts.user_id')
             ->select('posts.*', 'users.name as user_name')
             ->where('posts.comments', '<>', NULL)
             ->get();

@注意:如果您使用soft deletes,可能需要添加where('posts.deleted_at', null)

答案 1 :(得分:0)

您可以更轻松地遵守Laravel的命名关系惯例。

Post有许多Comments,属于User。鉴于此设置:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

class Comment extends Model
{
   public function post()
   {
       return $this->belongsTo(Post::class);
   }

   public function user()
   {
       return $this->belongsTo(User::class);
   }
}

然后,您可以查询帖子的评论和用户:

$comments = $post->comments()->with('user')->get();

如果您一直希望用户返回评论,您也可以在user上急切加载comments关系:

class Comment extends Model
{
    protected $with = ['user'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

然后您的查询将被简化:

$comments = $post->comments;

希望这可以帮助你!!

答案 2 :(得分:0)

经过几天的搜索终于得到了答案,我可以合并这样的查询:

$posts = Post::with(['comments','users'])->findOrFail($id);

但在Post Model中功能不是&#34;用户&#34;但是&#34;用户&#34;。