不直接相关的表之间的关系 - Laravel Eloquent

时间:2021-03-20 17:58:50

There are 4 tables: users, owners, groups, requests

共有4个表:用户,所有者,组,请求

There is no direct relation between owners and requests and I'm looking for a way to do something like this: $onwer->requests, to get all requests related to an owner.

所有者和请求之间没有直接关系,我正在寻找一种方法来执行以下操作:$ onwer-> requests,以获取与所有者相关的所有请求。

Here is how things works:

事情是这样的:

Every user is in a group, each group is owned by an owner, requests will be created by users and each request is for a (related to/ within a) group.

每个用户都在一个组中,每个组都由一个所有者拥有,请求将由用户创建,每个请求都是针对一个(与一个内部相关的)组。

Tables are like this:
owners: id,username
groups: id,name,owner_id,year users: id,username
group_user: id,group_id,user_id
requests: id,group_id,user_id,desc

表是这样的:owner:id,username groups:id,name,owner_id,year users:id,username group_user:id,group_id,user_id requests:id,group_id,user_id,desc

It's easy to create relation between owners and groups, or between requests and users, but how can I get all related requests to an owner? another thing is that I should be able to get all requests belong to a owner which are in a group with a where statement like year=something.

在所有者和组之间,或在请求和用户之间创建关系很容易,但是如何向所有者提供所有相关请求?另一件事是我应该能够获得属于所有者的所有请求,这些所有者都在一个具有诸如year = something之类的where语句的组中。

For now I'm doing something stupid like this:

现在,我正在做一些像这样的蠢事:

There is one to many relation between group and requests, so i can get all requests from a group. (group hasMany request)

组和请求之间存在一对多关系,因此我可以从组中获取所有请求。 (组有多个请求)

$groups = Group::where('owner_id', $owner_id)->get();

foreach($groups as $group)
   foreach($group->requests as $request)
      if($request->year == 2016)
          $requests[] = $request;

1 个解决方案

#1


1  

For anybody else looking for the same thing, the concept behind this is called hasManyThrough by Laravel.

对于任何寻找同样事物的人来说,这背后的概念被Laravel称为hasManyThrough。

In this case, we would have the following function at the Owner's Class Model

在这种情况下,我们将在所有者的类模型中具有以下功能

public function requests() {
    return $this->hasManyThrough(\App\Request::Class, \App\Group::Class);
}

The logic here is that the Owner has a lot of Requests (1st parameter) through the Group class (2nd parameter).

这里的逻辑是所有者通过Group类(第二个参数)有很多请求(第一个参数)。

#1


1  

For anybody else looking for the same thing, the concept behind this is called hasManyThrough by Laravel.

对于任何寻找同样事物的人来说,这背后的概念被Laravel称为hasManyThrough。

In this case, we would have the following function at the Owner's Class Model

在这种情况下,我们将在所有者的类模型中具有以下功能

public function requests() {
    return $this->hasManyThrough(\App\Request::Class, \App\Group::Class);
}

The logic here is that the Owner has a lot of Requests (1st parameter) through the Group class (2nd parameter).

这里的逻辑是所有者通过Group类(第二个参数)有很多请求(第一个参数)。