[英]How do i use one to many relationship within Laravel 8 Middleware?
I have a Users
and Roles
table in my database.我的数据库中有一个Users
和Roles
表。 One user
can have many roles
.一个user
可以有多个roles
。 I am using Laravel 8, I want to be able to return all roles
for that user
within the middleware (I am using inertia.js - handleinertiarequest.php
).我正在使用 Laravel 8,我希望能够在中间件中返回该user
所有roles
(我正在使用惯性.js - handleinertiarequest.php
)。
id ID | role角色 | user_id用户身份 |
---|---|---|
1 1 | super_admin超级管理员 | 3 3 |
2 2 | admin行政 | 3 3 |
3 3 | user用户 | 3 3 |
id ID | name名称 |
---|---|
1 1 | Some name一些名字 |
2 2 | Some other name别的名字 |
3 3 | Joe Bloggs乔·博格斯 |
User.php
):用户模型( User.php
):public function userroles()
{
return $this->hasMany(Roles::class);
}
Roles.php
):角色模型( Roles.php
):public function user()
{
return $this->belongsTo(User::class);
}
HandleInertiaRequest.php
: HandleInertiaRequest.php
:public function share(Request $request)
{
return array_merge(parent::share($request), [
'auth' => function () use ($request) {
return [
'user' => $request->user() ? [
'id' => $request->user()->reference,
'first_name' => $request->user()->first_name,
'last_name' => $request->user()->last_name,
'role_staff' => \App\Models\Roles::select('id'),
] : null,
];
},
]);
}
Layout.vue
: Layout.vue
:{{ $page.props.auth.user.role_staff }}
So if I am logged in as Joe Bloggs
( id = 3
), I want it to return 3 roles
(or even just 1, if using the id
).因此,如果我以Joe Bloggs
( id = 3
) 身份登录,我希望它返回3 roles
(如果使用id
,甚至只有 1 个)。 But this doesn't return anything or show any errors.但这不会返回任何内容或显示任何错误。 What am i missing here?我在这里缺少什么? Thanks谢谢
Use this relationship method in user modal:在用户模式中使用这种关系方法:
public function userRoles()
{
$this->hasMany('App\Models\role_table_modal_name','user_id');
}
Then in controller/middleware call your User modal:然后在控制器/中间件中调用您的用户模式:
$ user_roles = User::find($id)->with('userRoles')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.