首页 > 解决方案 > 合并模型及其与结果的关系,如 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 中将收集与合并或推送结合起来,但我似乎无法做到正确。

至于为什么不使用连接查询,因为我想动态加载关系,所以关系并不总是被加载,但有时它们会加载。在加入查询时,我必须手动编写(据我所知):-)

也许有人可以指点我某个地方,或者也许有这样的包裹?

提前致谢

标签: laravellaravel-8eloquent-relationship

解决方案


你可以通过加入来做到这一点;

$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();

推荐阅读