AR获得自己的帖子和朋友帖子

时间:2012-11-21 21:55:46

标签: mysql codeigniter activerecord codeigniter-2

我有这些表格;

user - contains user_id | username | fullname | email etcc
user_followers - contains follow_id| user_id | follower_id | date etcc
posts - contains post_id | user_id | post | post_date 

我正在尝试抓住用户关注的用户和用户自己帖子的所有帖子。

我试过

$this->db->select('posts.*')->from('posts')
        ->join('user_followers', 'user_followers.user_id = posts.user_id', 'INNER')
        ->where('user_followers.follower_id', $user_id)->order_by('posts.post_date','desc');
    $query = $this->db->get(); 

但问题是,我无法从此查询中获取用户的帖子。我已经尝试过or_where等其他方法,我能够得到用户的帖子,只是数据增加了三倍:( 有人可以帮帮我吗? 非常感谢提前。

哦,在正常的Mysql中,它的;

SELECT  posts.*
FROM    posts
JOIN    user_followers
ON      user_followers.user_id = posts.user_id
WHERE   user_followers.follower_id = $user_id
ORDER BY
    posts.post_date DESC

3 个答案:

答案 0 :(得分:2)

- > where()支持将任何字符串传递给它,并且它将在查询中使用它,前提是您分别传递NULL和FALSE的第二个和第三个参数。这告诉CI不要逃避查询。 例如。

$where_query = "p.user_id = $user_id OR p.user_id IN (SELECT user_id FROM user_followers WHERE follower_id = $user_id)";
->where($where_query,NULL,FALSE);

或者,您可以查看此子查询库https://github.com/EllisLab/CodeIgniter/wiki/Subqueries

答案 1 :(得分:1)

SELECT  p.*
FROM    (
        SELECT  user_id
        FROM    user_followers
        WHERE   follower_id = $user_id
        UNION ALL
        SELECT  $user_id
        ) uf
JOIN    posts p
ON      p.user_id = uf.user_id

答案 2 :(得分:0)

为什么不进行子选择?

select * from posts 
where user_id IN (
    select user_followers.follower_id 
        from user_followers 
        where user_followers.user_id=$user_id) 
    OR posts.user_id = $user_id;