Home > Mobile >  Polymorphic relationships via a pivot table
Polymorphic relationships via a pivot table

Time:01-30

How to build relationships between models based on a screenshot?

Screen

Upd: I would like to receive payment items via $payment->items().

CodePudding user response:

There is an example here: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-polymorphic-table-structure

Since your table names and column names do not follow the conventions set by Laravel, a few extra parameters are needed.

class Good extends Model
{
    protected $table = 'good';

    public function payments()
    {
        return $this->morphToMany(Payment::class, 'entity', 'item_payments');
    }
}
class Service extends Model
{
    protected $table = 'service';

    public function payments()
    {
        return $this->morphToMany(Payment::class, 'entity', 'item_payments');
    }
}
class Payment extends Model
{
    public function services()
    {
        return $this->morphedByMany(Service::class, 'entity', 'item_payments');
    }

    public function goods()
    {
        return $this->morphedByMany(Good::class, 'entity', 'item_payments');
    }
}
  •  Tags:  
  • Related