我想在我的网站上创建一个类似分享的功能。我有这些桌子
用户
- 用户身份
- 全名
- 用户名等
帖子
- post_id
- 用户身份
- 邮政
- orig_post_id
- 日期
USER_FOLLOWERS
- follow_id
- 用户身份
- 追随者ID
- 日期
我有这个查询来从当前用户关注的用户中选择帖子。
//user_id from session data
$user_id = $this->session->userdata('user_id');
$sql = "SELECT p.*,u.fullname,u.username
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
JOIN users u
ON u.user_id = p.user_id
ORDER BY p.post_date DESC";
$query = $this->db->query($sql);
if ($query) {
foreach ($query->result() as $row) {
$branch_id = $row->orig_post_id;
$post_array[] = array(
'post_id' => $row->post_id,
'user_id' => $row->user_id,
'post' => $row->post,
'is_branch_of_id' => $branch_id,
'post_date' => $row->post_date,
'fullname' => $row->fullname,
'username' => $row->username
);
#i would explain what i'm tying to do here below
if ($branch_id != 0) {
$branch_array = array();
#this contains the orignal posts user id
$user_branch_id = $this->postid_return_user_id($branch_id);
$branch_data = $this->branch_query($user_branch_id, $branch_id);
$branch_array[] = array(
'branch_uname' => $branch_data->username,
'branch_fname' => $branch_data->fullname,
'orig_post' => $branch_data->post
);
$post_obj = (object)array_merge($branch_array, $post_array);
} else {
$post_obj = (object)$post_array;
}
}
return $post_obj;
然后分支查询
public function branch_query($orig_post_user_id, $orig_post_id)
{
$sql = "SELECT users.username,users.fullname,posts.post,posts.post_id
FROM users u
JOIN posts p
ON p.user_id = u.user_id
WHERE u.user_id = $orig_post_user_id
AND p.post_id = $orig_post_id";
$q = $this->db->query($sql);
return ($q)?$q->result():array();
}
第一,在 post_array 中获取我需要的数据。
如果字段 orig_post_id 不为 0,则表示该帖子是由另一个帖子的用户分享的。我创建了另一个名为 branch_array 的数组,分支数组旨在包含原始帖子的用户用户名、全名和原始帖子本身。这就是分支查询的用武之地。通过分支查询,我传递原始用户用户 ID 和原始帖子 ID,然后它返回原始帖子用户用户名、全名和帖子本身。然后我在分支数据变量中得到它并将其放入分支数组中。
现在我尝试将分支数据合并到 post_array 并将合并的数组转换为对象。我想要的输出看起来像这样;
场景 1,当 orig_post_id 不为 0 时
$post_obj = new stdClass([post_id] => 4,
[user_id] => 2,
[post] => ok ginny,
[orid_post_id] => 3,
[post_date] => some timestamp,
[fullname] => Harry Potter,
[username] => avadakedevra,
[branch_uname] => ginny,
[branch_fname] => Ginny Potter
[orig_post] => stop it harry
)
如您所见,分支数据已合并。场景 2,当 orig_post_id = 0 时
$post_obj = new stdClass([post_id] => 3,
[user_id] => 1,
[post] => stop it harry,
[orid_post_id] => 0,
[post_date] => some timestamp,
[fullname] => Ginny Potter,
[username] => ginny
)
现在它只获取一个分支数据并将其放在对象之外。任何帮助将不胜感激。对不起,长度。正如你可以从哈利波特的帖子中看出的那样,我真的要哭了,哈哈,再次感谢。