我正在将现有的 Twitter 克隆玩具项目转换为 Laravel 4。我之前使用过 codeigniter 框架,Eloquent ORM 是我接触过的第一个 ORM。
所以我对如何进行一些预先查询感到困惑,
以下查询是获取所有由 current_user
关注的 users
创建的 posts
。此存储过程片段工作正常。
BEGIN
SELECT
tbl_users.id as user_id,
tbl_users.display_name,
tbl_users.username,
tbl_posts.id as post_id,
tbl_posts.post_text,
tbl_posts.`timestamp`
FROM tbl_posts , tbl_users
WHERE tbl_posts.user_id IN (
SELECT tbl_followers.destination_user_id FROM tbl_followers
WHERE tbl_followers.source_user_id = xSource_user_id
)
AND tbl_posts.user_id = tbl_users.id
ORDER BY tbl_posts.id DESC
LIMIT xLimit;
END
表结构如下:
用户
: (id)
帖子
: (id,src_user_id [FK], post_text )
关注者
:(id,dest_user_id [FK],src_user_id [FK])
我最好的猜测是:
Post::where('user_id', 'IN' , Follower::where('from_user_id','=','1'))->toSql();
我已将以下关系添加到用户模型
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
最佳答案
您需要使用 lists() 来获取数组形式的结果
Post::whereIn('user_id', Follower::where('from_user_id','=','1')->lists('id'))->toSql();
关于php - 如何在 Laravel 4 的 Eloquent ORM 中使用 IN 或 Nesting of queires,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598001/