通过几个表的关系

时间:2018-03-07 21:31:04

标签: php laravel

告诉我,我有Eloquent模特:

- countries; 
- regions;
- cities;
- schools;
- users;

关系:

Countries -> hasMany -> Regions<br>
Regions -> hasMany -> Cities<br>
Cities -> hasMany -> Schools<br>
Schools <-> hasManyToMany <-> Users (through table)

如何通过实际情况从国家/地区获取所有用户?

2 个答案:

答案 0 :(得分:0)

尝试做这样的事情

您总是可以循环遍历集合,就像它们是数组一样

$user = \App\User::all();
$users = array();
foreach ($user->Schools as $schools)
{
   foreach ($schools->city as $cities)
   {
      foreach ($cities->region as $regions)
      {
         foreach ($regions->country as $country)
         {
             if ($country == 'YourCountry'); {
             $users [] = $users->name;
             }

根据$users数组中的国家/地区名称,您将获得所有用户。

不确定,这正是您正在寻找的,但您明白了。

答案 1 :(得分:0)

试试这个。

$country = \App\Country::find(1);
$users = [];

foreach ($country->regions as $region)
{
    foreach ($region->cities as $city)
    {
        foreach ($city->schools as $school)
        {
            $users [] = $scholl->users;
        }
    }
}

$users将容纳ID为1的国家/地区的所有用户。