获取所有帖子,并检查用户是否喜欢每个帖子 [英] Get all posts and check if user liked each post
本文介绍了获取所有帖子,并检查用户是否喜欢每个帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个雄辩的查询,以获取所有帖子,并检查用户是否喜欢这些帖子中的每一个.
I'm trying to create an Eloquent query that fetches all posts and checks if the user liked each of those posts.
我有以下型号:
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';
}
还有典型的 User
模型.
我的数据库结构如下:
帖子
表:
+----+---------+---------+
| id | user_id | message |
+----+---------+---------+
用户
表:
+----+----------+
| id | username |
+----+----------+
喜欢
表:
+----+---------+---------+
| 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);
}));
谢谢!
推荐答案
如何通过实际用户的ID过滤posts表和likes表之间的左联接?
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 :)
这篇关于获取所有帖子,并检查用户是否喜欢每个帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文