阅读(1296) (6)

Laravel 8 动态关联

2021-07-08 09:44:44 更新

您可以使用 resolveRelationUsing 方法在运行时定义 Eloquent 模型之间的关系。 虽然通常不建议在常规应用程序开发中使用它,但是在开发 Laravel 软件包时,这有时可能会很有用:

use AppModelsOrder;
use AppModelsCustomer;

Order::resolveRelationUsing('customer', function ($orderModel) {
    return $orderModel->belongsTo(Customer::class, 'customer_id');
}); 

注意:定义动态关系时,请始终为 eloquent 的关联方法提供显式的键名。