Get all posts and check if user liked each post

て烟熏妆下的殇ゞ 提交于 2021-01-28 21:55:11

问题


I'm trying to create an Eloquent query that fetches all posts and checks if the user liked each of those posts.

I have the following models:

Post.php

class Post extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

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

    public function likes()
    {
        return $this->hasMany('Like');
    }
}

Like.php:

class Like extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'likes';
}

And your typical User model as well.

My DB structure is the following:

posts table:

+----+---------+---------+
| id | user_id | message |
+----+---------+---------+

users table:

+----+----------+
| id | username |
+----+----------+

likes table:

+----+---------+---------+
| id | post_id | user_id |
+----+---------+---------+

Right now, my query only returns all posts, but how can I modify it to return all posts and check if the user liked each post?

Route::get('/', array('as' => 'index', function()
{
    $posts = Post::all();

    return View::make('index')->with('posts', $posts);
}));

Thanks!


回答1:


What about a left join between the posts table and the likes table, filtering by the actual user's id?

$post = DB::table('post')
                 ->select(DB::raw('message, likes.user_id IS NOT NULL as liked'))
                 ->leftJoin('likes', 'users_id', '=', 'likes.user_id')
                 ->where('likes.user_id', '=', $curent_user_id)  
                 ->get();

I have no way to test it now, but I hope it might give you some inspiration :)




回答2:


You can grab the likes with the post for that specific user. Try this..

Post::with(['likes' => function() use ($user_id) { $q->where('user_id','=', $user_id); }])->all();

It will return blank array if user haven't like the post.



来源:https://stackoverflow.com/questions/31059948/get-all-posts-and-check-if-user-liked-each-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!