2016-08-19 115 views
0

我有一个默认的认证表用户和另一个表user_profilesLaravel 5.2如何从两个或多个表从关系

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

我使用连接这两个表中获取值的许多一对多的关系 对于这一点,我增加在两个模型类 - 用户和用户配置关系

// 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. 如何将这些数据从多个表中显示到视图表单中?
+0

什么不工作方式?你有什么错误吗? – jaysingkar

+0

@ jaysingkar不,没有错误。当我调试输出iam越来越null数组 –

+0

@ jaysingkar当我尝试\应用程序用户:: find(1) - > userProfiles() - > get(); 我越来越空阵列[2016-08-19 13:53:55] local.DEBUG:[] –

回答

1

您已经定义的关系错在你的用户模型:交换user_iduser_profile_id

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

非常感谢。完美的工作.. 我有另一个dilut,有没有什么办法可以在一个单一的查询中获得这两个表数据,我是从cakephp背景,蛋糕是可能的。 –

+0

我想你可以使用'with()'方法 – jaysingkar

相关问题