【发布时间】:2015-06-25 20:14:43
【问题描述】:
我正在尝试创建一个 Eloquent 查询来获取所有帖子并检查用户是否喜欢这些帖子。
我有以下型号:
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 模型。
我的数据库结构如下:
posts表:
+----+---------+---------+
| id | user_id | message |
+----+---------+---------+
users表:
+----+----------+
| id | username |
+----+----------+
likes表:
+----+---------+---------+
| id | post_id | user_id |
+----+---------+---------+
目前,我的查询只返回所有帖子,但我如何修改它以返回所有帖子并检查用户是否喜欢每个帖子?
Route::get('/', array('as' => 'index', function()
{
$posts = Post::all();
return View::make('index')->with('posts', $posts);
}));
谢谢!
【问题讨论】:
-
您需要在每个帖子的基础上执行此操作。或者使用连接等创建自定义原始查询。
标签: laravel laravel-4 eloquent