【问题标题】:Laravel eager loading - one to many relationLaravel 急切加载 - 一对多关系
【发布时间】:2021-12-01 20:10:00
【问题描述】:

laravel 开发。

我有三个 表,比如说 A、B、C

A
-----------
-id
-main_location_id // **main location entry = 1**

B
-----------
-id
-a_id
-allocated_qty

C
-----------    
-id
-a_id
-location_id // **main location enrty + other locations enrty- 1,2,3**
-total_qty
-aval_qty

关系:

表A有很多B

表A也有很多C

查询:

A::with(['B'])
->with(['C']) // here I got all location object from C tables, but I only want main_location_id = location_id data object + its qty
->where('a.id', 1)
->first();

我不明白如何从表 C 到表 A

获取 location_id、total_qty、aval_qty

其中有 c.location_id = a.main_location_id

连我自己都不知道自己做得对不对?

这可能吗?

请帮帮我

非常感谢!

【问题讨论】:

  • 你必须查询tabler C并用查询过滤它,查询是指A。示例$c = C::with(['A' => fn ($query) => $query->where('id', '=', 'a_id')])->get();见laravel.com/docs/8.x/…

标签: laravel one-to-many eager-loading has-many


【解决方案1】:

这取决于您如何定义这种关系。如果你像这样在代码中定义一个关系:

// models/A.php
public function c() {
    return $this->hasMany(C::class);
}

它会默认使用A的主键,即id,所以当Laravel给表名加上前缀时,它会变成a_id。然后,这变成了一个包含许多 Cs 的数组,它们属于 A 到 A.id = C.a_id。您必须向hasMany 传递更多参数来定义您自己的密钥。

但是,您需要的关系似乎是hasOne 关系:您的A 只有一个C 到A.main_location_id = C.location_id。因此,您可以使用手动键定义 hasOne,如下所示:

// models/A.php
public function c() {
    return $this->hasOne(C::class, 'location_id', 'main_location_id');
}

如果那是错误的键,则必须将额外的参数传递给hasOne() 关系定义。

如果您需要这两种关系,只需重命名函数(如果您有正确的表名,请使用复数和单数形式),例如,您可以使用 A::query()->with(['c', 'singleC'])

【讨论】:

  • 我已经尝试过你的建议 // models/A.php public function c() { return $this->hasOne(C::class, 'location_id', 'main_location_id'); } 但它给了我 C 表中的第一次出现记录这是错误的我需要 C 表中相同的 a_id+ mfg_location_id 记录
猜你喜欢
  • 2014-06-21
  • 1970-01-01
  • 2019-08-09
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2021-07-06
相关资源
最近更新 更多