Laravel 5.6急于加载特定列不会返回任何内容 [英] Laravel 5.6 Eager Loading specific column returns nothing
问题描述
我有两个类,Product
和ProductFormat
.该关系已正确定义,即我的产品hasMany
ProductFormat.
I have two classes, Product
and ProductFormat
. The relationship is defined properly, my Product hasMany
ProductFormat.
public function formats()
{
return $this->hasMany(ProductFormat::class);
}
当我尝试使用特定列加载关系时,请按照文档中的说明进行操作( https://laravel.com/docs/5.6/eloquent-relationships#eager-loading ),它没有按预期运行.
When I'm trying to eager load the relationship with specific columns, as followed in the documentation (https://laravel.com/docs/5.6/eloquent-relationships#eager-loading), it's not working as expected.
例如,当我执行以下操作时:
For example, when I do the following:
Product::with('formats:id,upc')->get();
我得到我的产品,到处都是空格式.
I get my products, with empty formats everywhere.
{
id: 1,
formats: [ ]
}
但是,如果我执行以下操作:
However, if I do the following:
Product::with('formats')->get();
我得到了预期的格式,但是有太多不需要的列.
I get the expected formats, but it has too many non needed columns.
{
id: 1,
formats: [
{
id: 1,
upc: "101862422191",
weight: 8.46,
weight_unit: "kg"
}
]
}
推荐答案
您始终需要选择关系中涉及的外键/主键.也在急切加载中获取product_id,它将正常工作
You always need foreign key/primary key, involved in the relation, to be selected. fetch product_id too in eager load and it will work
Product::with('formats:id,upc,product_id')->get();
这篇关于Laravel 5.6急于加载特定列不会返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!