Laravel 8 定义中间表模型
如果你想定义一个自定义模型来表示关联关系中的中间表,可以在定义关联时调用 using 方法。自定义多对多中间表模型都必须扩展自 Illuminate\Database\Eloquent\Relations\Pivot 类,自定义多对多(多态)中间表模型必须继承 Illuminate\Database\Eloquent\Relations\MorphPivot 类。例如,我们在写 Role 模型的关联时,使用自定义中间表模型 RoleUser:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* 拥有此角色的所有用户
*/
public function users()
{
return $this->belongsToMany('App\Models\User')->using('App\Models\RoleUser');
}
} 当定义 RoleUser 模型时,我们要扩展 Pivot 类:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUser extends Pivot
{
//
} 你可以组合使用 using 和 withPivot 从中间表来检索列。例如,通过将列名传递给 withPivot 方法,就可以从 UserRole 中间表中检索出 created_by 和 updated_by 两列数据:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* 拥有此角色的用户
*/
public function users()
{
return $this->belongsToMany('App\Models\User')
->using('App\Models\RoleUser')
->withPivot([
'created_by',
'updated_by',
]);
}
} 注意:
Pivot模型可能不使用SoftDeletes特性。 如果您需要软删除数据关联记录,请考虑将您的数据关联模型转换为实际的Eloquent模型。