I have two models InvoiceTotal
and MeterTariff
with inside the InvoiceTotal model a one to many relationship
public function meter_tariff() {
return $this->belongsTo(MeterTariff::class);
}
I'm querying all the unique meter_tariff rows based on invoice_id's using the with
and distinct
functions.
$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();
This is working fine. The result is an array with unique rows based on the meter_tariff_id but I'm getting all the columns from InvoiceTotal
and the MeterTariff
relationship.
I want to limit the selected columns to id
and name
from the MeterTariff
relationship.
I've tried the following code.
Select:
$meter_tariffs = InvoiceTotal::with('meter_tariff')
->whereIn('invoice_id', $validatedData['invoice_ids'])
->distinct('meter_tariff_id')
->select('meter_tariff:id,name')
->get();
Query inside the with:
$meter_tariffs = InvoiceTotal::with(['meter_tariff' => function($query) {
$query->select('id', 'name');
}])
->whereIn('invoice_id', $validatedData['invoice_ids'])
->distinct('meter_tariff_id')
->get();
Selection in the with:
$meter_tariffs = InvoiceTotal::with('meter_tariff:id, name')
->whereIn('invoice_id', $validatedData['invoice_ids'])
->distinct('meter_tariff_id')
->get();