如何在Laravel 5.4中使用多重关系

时间:2019-03-15 12:01:08

标签: php laravel

在我的应用中,我定义了关系(配置文件,用户,级别),但是当我获取数据时,它显示了错误(Trying to get property 'email' of non-object),我该如何提前解决此感谢。

这是用户模型

public function profile()
{
     return $this->hasOne(Profile::class, 'user_id');
}

个人资料模型

public function user()
{
    return $this->belongsTo(User::class, 'id');
}
public function level()
{
   return $this->belongsTo(Level::class, 'id');
}

关卡模型

public function profile()
{
  return $this->hasOne(Profile::class, 'level_id');
}

这是Controller ProfileController

$users = Profile::with(['user', 'level'])->where('is_bd_partner', 'Yes')->get();
        foreach ($users as $key => $value) 
        {
            echo $value->first_name.'<br>';
            echo $value->last_name.'<br>';
            echo $value->user->email.'<br>';
            echo $value->level->level.'<br>';
        }

1 个答案:

答案 0 :(得分:2)

请注意,belongsTo将foreign_key作为第一个参数。 因此,您应该将配置文件模型更改为

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}
public function level()
{
   return $this->belongsTo(Level::class, 'level_id');
}

了解更多here