Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
Laravel Eloquent select only columns from relationship

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();
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use pluck to get only the selected columns - id and name from the MeterTariff relationship.

$meter_tariffs = InvoiceTotal::with('meter_tariff')->whereIn('invoice_id', $validatedData['invoice_ids'])->distinct('meter_tariff_id')->get()->pluck('meter_tariff.id', 'meter_tariff.name')
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda