问题
I have these tables;
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
I’m trying to grab all the posts by the users the user is following and the user’s own posts.
I’ve tried
$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();
But the problem is, i’m not able to get the user’s posts from this query. I’ve tried other methods with or_where etc and i was able to get the user’s posts, only that the data was tripled :( Can someone please help me out here? Many Thanks in advance.
Oh in normal Mysql, its;
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
回答1:
->where() supports passing any string to it and it will use it in the query, provided you pass a second and third parameter of NULL and FALSE respectively. This tells CI not to escape the query. E.g.
$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);
Alternatively, you could check out this subquery library https://github.com/EllisLab/CodeIgniter/wiki/Subqueries
回答2:
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
回答3:
Why not a subselect?
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;
来源:https://stackoverflow.com/questions/13502671/ar-get-own-posts-and-friends-posts