[英]Display posts from followers and logged-in user
I want to display posts from the users being followed and the logged in user using a single PHP mysql query. 我想使用单个PHP mysql查询显示来自正在关注的用户和已登录用户的帖子。
I have three tables: 我有三个表:
- Users (id, name, password) -用户(ID,名称,密码)
- Posts (id, body, date, user_id) -帖子(id,正文,日期,user_id)
- Followers (id, user_id, follower_id) -关注者(ID,用户ID,关注者ID)
followers.follower_id = person who does the following followers.follower_id =执行以下操作的人
followers.user_id = person who is being followed followers.user_id =被追踪的人
$_SESSION['id'] = id of the logged in user $ _SESSION ['id'] =登录用户的ID
DB::query('
SELECT users.name, posts.body
FROM users, posts, followers
WHERE posts.user_id = followers.user_id
AND users.id = posts.user_id
AND followers.follower_id = :userid',
array(':userid'=>$_SESSION['id'])
);
But the query only shows posts from the users being followed, not from the logged in user. 但是查询仅显示来自所关注用户的帖子,而不显示来自已登录用户的帖子。 How do I fix this?
我该如何解决?
I have already created a relation between the posts table and the users table. 我已经在posts表和users表之间创建了一个关系。
CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`body` varchar(160) NOT NULL DEFAULT '',
`user_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
You need to include 2 criteria in your WHERE
clause: Either the creator of the post matches your :userid
variable, or the follower matches your :userid
. 您需要在
WHERE
子句中包括2个条件:帖子的创建者匹配您的:userid
变量,或者关注者匹配您的:userid
。
Please use current join syntax: This makes your query a lot easier to read. 请使用当前的联接语法:这使您的查询更易于阅读。
Your final query should be something like this (I'm excluding the PHP part): 您的最终查询应该是这样的(我不包括PHP部分):
SELECT users.name, posts.body
FROM posts
INNER JOIN users ON
users.id = Posts.user_id
-- use left join to handle when a
-- user has no followers
LEFT JOIN Followers ON
Followers.user_id = users.user_id
WHERE
users.id = :userid
OR followers.follower_id = :userid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.