我已经使用 PHP 和 Mysql 构建了一个类似 Twitter 的关注系统,我想按照用户关注用户的顺序列出用户拥有的关注者。有两个与此操作相关的关系表:USERS 和 FOLLOW。
user_id
被关注者。
follow_id
跟随的人。
创建
以下事件发生的日期。
关注
--------------------------------------------------
|user_id |follow_id | created |
--------------------------------------------------
| 23 | 5 |2016-08-09 |
--------------------------------------------------
用户
--------------------------------------------------
|user_id | name |
-------------------------------------------------
| 5 |John Doe|
--------------------------------------------------
这是用于获取特定用户的关注者的 php Mysql 函数。
<?php
public static function find_followers($user_id){
global $database;
$followers_ids = array();
$sql = "SELECT user_id
FROM follow
WHERE followed_id = '{$user_id}'
ORDER BY created";
$result = $database->query($sql);
while($follower = $database->fetch_array($result)){
array_push($followers_ids, $follower['user_id']);
}
if(count($followers_ids)){
$id_strings = join(',', $followers_ids);
$sql = "SELECT * FROM users WHERE id IN ($id_strings)";
$followers = self::find_by_sql($sql);
return $followers;
}
}
?>
显示关注者的代码
<?php
$followers = find_followers($id);
foreach($followers as $follower){
echo $follower->full_name() . "followed you.<br/>";
?>
目前,关注者列表按创建用户的创建顺序排序,我想根据他们关注用户的时间顺序显示它们。如何做到这一点?
提前致谢!
最佳答案
您可以在两个表上使用连接,而不是多次调用数据库。 SQL 将是:
SELECT user.user_id, user.name /*The user that is followings details*/
FROM users
JOIN follow ON user.user_id = follow.follow_id /*You want the info for follower*/
WHERE follow.user_id = '{$user_id}' /*Only where the user is this user*/
ORDER BY follow.created /*Based on question this is the date a follow happened*/
现在PHP可以变成(假设$database是mysqli
但不确定):
<?php
public static function find_followers($user_id){
global $database;
$followers_ids = array();
$sql = "SELECT user.user_id, user.name
FROM users
JOIN follow ON user.user_id = follow.follow_id
WHERE follow.user_id = '{$user_id}'
ORDER BY follow.created";
//If $user_id is user input you should do a prepared statement.
$result = $database->query($sql);
$followers = $database->mysqli_fetch_all($result);
return $followers;
}
}
?>
您的 View 可以保持不变:
<?php
$followers = find_followers($id);
foreach($followers as $follower){
echo $follower->full_name() . "followed you.<br/>";
}
?>
关于php - 如何根据另一个表参数以特定顺序显示来自一个 MySQL 表的一组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982859/