Search code examples
laraveleloquentpolymorphic-relationship

Selecting fields from polymorphic relationship in DB


I have an Order model with a polymorphic customer relationship to Parent and School. My goal now is to query the orders and generate a report including the name and email of the customer. Both name and email fields are present in Parent and School.

Order has:

public function customer()
{
    return $this->morphTo();
}

Parent and School both have:

public function orders()
{
    return $this->morphMany(Order::class, 'customer');
}

My query currently is:

$result = Order::query()
        ->with('customer')
        ->select(
             'orders.id',
             'amount'
          )->get();

dd($result->first()->toArray());

Result is:

array:6 [▼
  "id" => 1
  "amount" => "42.00"
  "customer" => null
]

I thought it would be possible to add customer.name and customer.email in the list of selected fields but Eloquent complains that the customer field customer.name cannot be found which makes sense?

How do I obtain the data in the related models?


Solution

  • For Laravel 8, you can see the link here.

    Then, your code would be:

    $result = Order::whereHasMorph(
        'orderable', // this is your polymorphic relationship you define
        [Parent::class, School::class], // your list of Models you want to query from the polymorphic relationship
        function (Builder $query) {
            $query->select('name', 'email');
        }
    )->get();
    

    That should do it.