codeigniter-4 - 如何将数组作为连接表返回
问题描述
我正在使用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。
如何包含与帖子关联的所有类别?
解决方案
推荐阅读
- r - ggplot堆积条形图问题
- python - Pandas:什么决定了 DatetimeIndex.intersection 的返回类型?
- swift - 框架内 NotificationServiceExtension 中的内存管理
- angular6 - Angular 6 - 使用服务在组件之间发送对象
- c# - ReadInnerXml 内存不足
- typescript - 如何在 TypeScript 中表达“以 T 为参数的函数 | 作为 T 的键的字符串”
- javascript - 将 react-native-charts-wrapper 导出为 PNG
- qt - LynxOS 是否支持 QT 和 QML?如果是,那么是哪个版本
- php - PHP AES 加密 JAVA 到 PHP - openssl_encrypt
- laravel - 排序hasMany关系