laravel - 合并模型及其与结果的关系,如 laravel 中的连接查询
问题描述
我是 Laravel 和编程的新手。我在加入模型及其关系时遇到问题,这是我的模型:
class MainClass extends Model
{
public function first()
{
return $this->hasMany(First::class);
}
public function second()
{
return $this->hasMany(Second::class);
}
public function third()
{
return $this->hasMany(Third::class);
}
}
当我尝试获取 MainClass 记录然后加载它的关系,如:
$main = Main::where('status', 'ready')->get()
$main->load(['first','second'])
这是我得到的:
[{
"id":"1",
"name":"First Person",
"status": "ready",
"first":[
{"main_id": "1", "prop":"One"},
{"main_id":"1", "prop":"Two"}],
"second":[
{"main_id": "1", "other":"Yes"},
{"main_id":"1", "other":"Two"},
{"main_id":"1", "other":"Three"}]
},{
"id":"5",
"name":"Fifth Person",
"status": "ready",
"first":[
{"main_id": "5", "prop":"Five"},
{"main_id":"5", "prop":"Six"}],
"second":[
{"main_id": "5", "other":"Laptop"},
{"main_id":"5", "other":"Pc"}]
}]
我怎样才能合并这种关系,所以结果就像连接查询, 这就是我想要的:
[{
"id":"1",
"name":"First Person",
"status": "ready",
"prop":"One",
"other:"Yes"
},{
"id":"1",
"name":"First Person",
"status": "ready",
"prop":"Two",
"other":"Two"
}]
我知道有一种方法可以在 laravel 中将收集与合并或推送结合起来,但我似乎无法做到正确。
至于为什么不使用连接查询,因为我想动态加载关系,所以关系并不总是被加载,但有时它们会加载。在加入查询时,我必须手动编写(据我所知):-)
也许有人可以指点我某个地方,或者也许有这样的包裹?
提前致谢
解决方案
你可以通过加入来做到这一点;
$main = Main::query()->select(['main.id', 'main.name', 'main.status', 'f.prop', 's.other', 't.blabla'])
->leftJoin('first as f', 'f.main_id', 'main.id')
->leftJoin('second as s', 's.main_id', 'main.id')
->leftJoin('third as t', 't.main_id', 'main.id')
->where('main.status', 'ready')
->get();
推荐阅读
- javascript - Puppeteer 问题:页面内容更改后,无法按两次相同的按钮(但按钮 ID 没有)
- swift - 需要帮助了解如何使用多级函数调用处理完成处理程序
- sas-macro - SAS 宏读取多个没有标题的原始数据文件并为每个原始数据文件创建多个 SAS 数据集
- function - 如何在 phpMyAdmin 中获得“全屏”常规编辑?
- javascript - 使用正则表达式,以时间格式分隔时间值
- javascript - 如何从 php 获取参数值到 Blade 模态弹出窗口?(Laravel 兰花)
- python - 在 matplotlib 3d 绘图中,plot_wireframe 中的参数 rcount、ccount、rstride 和 cstride 的意义是什么?
- c# - 字段 vs { get;set } vs { get=>field; set=>field = value;} - C# Unity
- javascript - 仅更改所有图像的不透明度,悬停的一张除外
- xml - 我想要一个逐对的节点列表,在这些节点上迭代而不是连接的文本节点