我有一个名为 User
的主模型,它返回应用程序的所有用户。
有一个名为 invites
的表,用于管理受邀访问被邀请者面板的用户。 invites
表因此链接到users
:
< img src="https://i.sstatic.net/iWQVB.jpg" alt="在此处输入图像描述">
所以我们有一个处理所有用户的通用 User
模型,以及其他两类用户:
- 患者:邀请租户的用户
- 租户:有权访问关联患者列表的用户
我想做的是使用雄辩的关系系统获取某个租户(登录用户)的患者列表,所以我不'不必每次都为连接编写查询。可以这样做吗?
目前,我尝试了这个:
class Patient extends User
{
use HasFactory;
//protected $table = 'users';
public function getList()
{
return $this->belongsToMany(User::class, 'invites', 'id', 'user_id');
}
}
但当然这种关系不起作用,因为应该执行的查询必须是这样的:
SELECT u.*
FROM users u
INNER JOIN invites i ON i.user_id = u.id
WHERE i.tenant_id = 1
其中 id 是我使用 laratrust auth 检索的当前登录用户的引用:auth()- >用户()->id
。
是否可以自动返回与登录用户关联的所有患者?所以简单地打电话:
Patient::query();
我怎样才能实现这一目标?
I have a main model called User
that returns all the users of the application.
There is a table called invites
which manages the users invited to access the invitee panel. The invites
table is thus linked to users
:
So we have a general User
model which handle all the users, and other two types of users:
- Patient: user who invited the tenant
- Tenant: user who has access to a list of associated patients
What I am trying to do is to fetch a patient list of a certain tenant (logged in user) using the eloquent relationship system, so I don't have to write a query for the join every time. Is it possible to do this?
At the moment, I tried this:
class Patient extends User
{
use HasFactory;
//protected $table = 'users';
public function getList()
{
return $this->belongsToMany(User::class, 'invites', 'id', 'user_id');
}
}
but of course this relationship not works because the query that should execute must be this:
SELECT u.*
FROM users u
INNER JOIN invites i ON i.user_id = u.id
WHERE i.tenant_id = 1
where id is the reference of the current user logged in which I retrieve using laratrust auth: auth()->user()->id
.
Would be possible to return all the patients associated to the logged in user automatically? So simply calling:
Patient::query();
How can I achieve this?
发布评论
评论(1)
为了实现这一点,您应该定义关系并反转多对多关系:
在您的用户模型中:
并在患者模型中通过反向belongToMany参数定义反向多对多关系:
要为每个模型使用身份验证ID,您有2个选项:
选项 1:
在用户表中添加名为 user_type 的列,其类型为 enum('tenant','patent') 并根据用户类型使用适当的模型
选项2:
通过使用自定义身份验证防护,请查看这篇文章
https://www.codecheef.org/article/laravel-8-login-with-custom-guard-example
To achieve that you should define relation and reverse many to many relation:
in your user model:
And in Patient model define reverse many to many relation by reverse belongToMany params :
To use the auth id for each model you have 2 option:
Option 1:
add column in users table that named user_type wich have type enum('tenant','patient') and depend user type use the appropriate model
Option 2:
by using custom auth guards , take look to this article
https://www.codecheef.org/article/laravel-8-login-with-custom-guard-example