Laravel 5.2如何从关系中获取两个或多个表中的值

时间:2016-08-19 10:24:41

标签: many-to-many laravel-5.2

我有一个默认的身份验证表用户和另一个表user_profiles

 user(id,email,password) 
 user_profiles(id,first_name,last_name,mobile)

我使用多对多关系连接这两个表 为此,我在模型类User和UserProfile

中添加了关系
   // User Model
 public function userProfiles()
  {
    return $this->belongsToMany('App\Models\UserProfile',  'user_user_profile', 
  'user_profile_id', 'user_id');
    }

 //UserProfile Model

 public function users()
    {
   return $this->belongsToMany('App\User', 'user_user_profile', 
  'user_profile_id', 'user_id');
  }

我尝试使用

通过用户表访问UserProfle详细信息
    $user=\App\User::find(1)->userProfiles()->get();

但没有工作,也尝试了

     /$user = \App\User::findOrFail(1)->with('userProfiles')->get();

这也行不通,请帮忙

  1. 获取user_profile表详细信息以及用户表
  2. 如何访问数据透视表(user_id,user_profile_id)值
  3. 如何将多个表中的这些数据显示到视图表单中?

1 个答案:

答案 0 :(得分:1)

您在用户模型中定义了错误的关系:swap user_iduser_profile_id

// User Model
 public function userProfiles()
  {
    return $this->belongsToMany('App\Models\UserProfile',  'user_user_profile', 
   'user_id' , 'user_profile_id');
    }