1

現在、「social_posts」テーブルから詳細を取得しており、そのタグ、いいねの数、および結果のオブジェクトに対する回答の数を追加しています。ループで余分なクエリを実行せずにこれを実行できる方法はありますか?

    $query = "SELECT * FROM social_posts JOIN users ON social_posts.user_id = users.id";
    $posts = $this->db->query($query);

    if ($posts->num_rows() > 0) {        
        foreach ($posts->result() as $p => $post) {                     
            // Get the question's tags
            $tags = $this->db->query("SELECT * FROM social_tags 
                WHERE post_id = ?", $post->post_id);

            // Get the number of likes
            $likes = $this->db->query("SELECT id FROM social_likes 
                WHERE post_id = ?", $post->post_id);

            // Get the number of answers
            $answers = $this->db->query("SELECT id FROM social_responses 
                WHERE post_id = ?", $post->post_id);

            $post->tags = $tags->result();
            $post->likes = $likes->num_rows();
            $post->answers = $answers->num_rows();
            $post->author = array(
                "firstname" => $post->firstname,
                "thumbnail" => $post->thumbnail,
            );
        }

        return $posts->result();
    } else {
        return FALSE;
    }
4

1 に答える 1

2

このSQLを試すことができます:

SELECT 
    social_posts.*,
    users.*,
    GROUP_CONCAT(social_tags.name) AS tags,
    COUNT(social_likes.id) AS likes,
    COUNT(social_responses.id) AS answers
FROM 
    social_posts 
        JOIN users ON social_posts.user_id = users.id
        LEFT JOIN social_tags ON social_tags.post_id = social_posts.id
        LEFT JOIN social_likes ON social_likes.post_id = social_posts.id
        LEFT JOIN social_responses ON social_responses.post_id = social_posts.id
GROUP BY
    social_posts.id

タグはカンマ区切りの文字列として取得されます。もちろん、データベースに合わせて列名を調整する必要があります。

于 2013-01-10T00:49:45.397 に答える