代码之家  ›  专栏  ›  技术社区  ›  Antonios Tsimourtos

拉威尔嵌套关系

  •  0
  • Antonios Tsimourtos  · 技术社区  · 7 年前

    用户可以有多个设备,每个设备可以有多个接口。

    我想让用户了解他的设备和每个设备的接口。

    用户模型

    class User extends Authenticatable
    {
        use Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password',
            'profile_image', 'retrieve_email', 'retrieve_sms'
        ];
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        public function devices()
        {
            return $this->hasMany('App\Device');
        }
    
    }
    

    class Device extends Model
    {
        public function interfaces()
        {
            return $this->hasMany('App\ModelInterface');
        }
    
        public function user()
        {
            return $this->belongsTo('App\User');
        }
    
    }
    

    模型接口模型

    class ModelInterface extends Model
    {
        public function device()
        {
            return $this->belongsTo('App\Device');
        }
    
        public function alerts(){
            return $this->hasMany('App\Alerts');
        }
    }
    

    如何获得用户界面?

    Auth::user()->devices returns all the devices and works.
    

    我怎么可能说

    Auther::user()->devices->interfaces
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   ceejayoz    7 年前

    你想看看 HasManyThrough 关系。

    “多通”关系为通过中间关系访问远程关系提供了方便快捷的方式。例如,一个国家/地区模型可能通过中间用户模型有许多Post模型。在本例中,您可以轻松地收集给定国家的所有博客文章。

    你的用户模型上有一些东西:

    return $this->hasManyThrough('App\Interface', 'App\Device');
    

    他们的设备。

        2
  •  0
  •   Manzurul Hoque Rumi    7 年前

    foreach(Auth::user()->devices as $device)
    {
       foreach($device->interfaces as $interface)
       {
           // do whatever you want
       }
    }
    
        3
  •  0
  •   Mihir Bhende    7 年前

    您可以使用:

    $id = Auth::user()->id;
    
    $userwithDetails = User::with('devices', 'devices.interfaces')->where('id', $id)->first();