首页 > 解决方案 > 如何将数组作为连接表返回

问题描述

我正在使用CodeIgniter 4并且试图从查询中获取以下结构响应:

posts: [
     { id: 1, title: 'foo', categories: [], tags: [] },
     { id: 2, title: 'test', categories: [], tags: [] }
]

我有这个表结构:

博客帖子

id | author_id | title | slug | content | status | created_at | updated_at

blog_post_meta

id | post_id | meta_key | meta_value

博客标签

id | title | slug | description 

博客类别

id | title | slug | parent_id | description

本质上,blog_post_meta允许我关联特定博客文章的多个类别:

1 | 1 | category | 5 <- category id
2 | 1 | category | 6
3 | 1 | tag      | 2 <- tag id
4 | 1 | tag      | 3

在上面的示例中,我已将两个类别和两个标签关联到 post_id 1,现在我试图将所有内容都包含在查询生成器中,因此我创建了这个函数:

public function getResource(string $search = '')
{
    $builder = $this->builder()
        ->select('blog_posts.id, blog_posts.title, blog_posts.created_at, bc.title as category_title, bt.title as tag_title')
        ->join('blog_post_meta bpm', 'blog_posts.id = bpm.post_id', 'left')
        ->join('blog_categories bc', 'bpm.meta_value = bc.id', 'left')
        ->join('blog_tags bt', 'bpm.meta_value = bt.id', 'left');

    $condition = empty($search)
        ? $builder
        : $builder->groupStart()
        ->like('blog_posts.title', $search)
        ->orLike('blog_posts.created_at', $search)
        ->groupEnd();

    $condition->groupBy('blog_posts.id');

    return $condition;
}

但是我只能返回一个类别标题和一个标签标题,即使这不起作用,实际上也总是返回 null。

如何包含与帖子关联的所有类别?

标签: codeigniter-4

解决方案


推荐阅读