Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda