问题
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