通过枢轴的多态关系 table

Polymorphic relationships via a pivot table

如何根据截图建立模型之间的关系?

Screen

更新:我想通过 $payment->items() 接收付款项目。

这里有一个例子: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-polymorphic-table-structure

由于您的 table 名称和列名称不遵循 Laravel 设置的约定,因此需要一些额外的参数。

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');
    }
}