【问题标题】:Laravel Eloquent select only columns from relationshipLaravel Eloquent 仅从关系中选择列
【发布时间】:2021-12-24 23:24:28
【问题描述】:

我有两个模型 InvoiceTotal 和 MeterTariff 在 InvoiceTotal 模型中是一对多关系

public function meter_tariff() {
    return $this->belongsTo(MeterTariff::class);
}

我正在使用with 和distinct 函数根据invoice_id 查询所有唯一的meter_tariff 行。

$validatedData = $request->validate([
    'invoice_ids' => ['required', 'array'],
    'invoice_ids*' => ['exists:invoices, id']
]);

$meter_tariffs = InvoiceTotal::with('meter_tariff')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();

这工作正常。结果是一个基于meter_tariff_id 具有唯一行的数组,但我从InvoiceTotal 和MeterTariff 关系中获取所有列。

我想将MeterTariff 关系中的选定列限制为id 和name。

我试过下面的代码。

选择:

$meter_tariffs = InvoiceTotal::with('meter_tariff')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->select('meter_tariff:id,name')
    ->get();

在with里面查询:

$meter_tariffs = InvoiceTotal::with(['meter_tariff' => function($query) {
        $query->select('id', 'name');
    }])
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();

在with中选择:

$meter_tariffs = InvoiceTotal::with('meter_tariff:id, name')
    ->whereIn('invoice_id', $validatedData['invoice_ids'])
    ->distinct('meter_tariff_id')
    ->get();

【问题讨论】:

  • @miken32 我看到了一些我尝试过的答案。它返回关系表的特定列,但它也返回“主”表中的所有列,在这种情况下,我只需要关系表中的列,而不需要主表中的列
  • @Thore ,接近你想要的,你可以简单地在 ->get() 之后添加 ->map->meter_tariff
  • @steven7mwesigwa 就是这样!谢谢!!

标签: php laravel eloquent


【解决方案1】:

您可以使用 pluck 仅从 MeterTariff 关系中获取选定的列 - id 和 name。

$meter_tariffs = InvoiceTotal::with('meter_tariff')->whereIn('invoice_id', $validatedData['invoice_ids'])->distinct('meter_tariff_id')->get()->pluck('meter_tariff.id', 'meter_tariff.name')

【讨论】:

  • 但pluck 将返回一个数组而不是集合。
  • 通过 pluck 我得到一个对象而不是数组 {"ALLE":1,"T03ILM":3,"T01DIR":4,"T17LVA":13,"T15L6P":15} 加上它似乎仅限于一个/两个值。如果我添加第三个值,它会忽略最后一个。
猜你喜欢
  • 2013-04-03
  • 2015-10-14
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2017-05-23
  • 2019-03-04
相关资源
最近更新 更多