Home > front end >  How to select specific column from parent and child in laravel
How to select specific column from parent and child in laravel

Time:11-04

Please see my code below.

Controller

$orders = Order::with('product:id,name')
    ->select([
            'id',
            'order_number',
            'ordered_on',
            'status',
            'total'
        ])
        ->where('customer_id', session('customer_id'))
    ->orderBy('ordered_on', 'DESC')
        ->paginate(6);
    dd($orders);

Order model

public function product()
{
  return $this->belongsTo(Product::class);
}

The result above returns null when you check the product relationship data.

What I need

Select specific columns from Order model, then select specific columns from product relationship.

CodePudding user response:

You need to add the foreign key that you are referencing:

->select([
    'product_id'
    ...
])
...

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

Docs: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-specific-columns

  • Related