如何访问自定义数据透视模型中的方法



我使用的是Laravel 8,并使用自定义数据透视模型进行多对多关系,如文档中所述。但是,我不知道如何访问我在自定义枢轴模型中创建的方法。

比方说,使用文档中提供的示例,我在RoleUser模型中创建了一些方法。我的问题是:如何从Role模型,从类似Role::find(1)->users()的模型访问这些方法?有可能吗?

提前谢谢!

与从pivot访问任何属性相同。

https://laravel.com/docs/8.x/eloquent-relationships#retrieving-中间表列

use AppModelsUser;

$user = User::find(1);

foreach ($user->roles as $role) {
echo $role->pivot->methodInPivot();
}

In Role模型定义关系。

class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}

重要信息:piot表必须为单数格式并按字母顺序排序。例如role_user

如果您定义为roles_user,则需要在角色模型中的用户关系中进行自定义映射。

在控制器中

public function funcName()
{
# You can use all the Eloquent methods like where, get, first etc...
$roles = Role::with('users')->get(); 
return view('view_name', compact('roles'));
}

在视图中

foreach($roles as $role)
{
Role name - {{$role->name}}
foreach($role->users as $user)
{
user name - {{$user->name}}
}
}

要访问数据透视表中的任何其他字段,可以使用->pivot前缀。Ex$user->pivot->created_at

最新更新