Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Laravel中使用eloquent从子表中获取值?_Laravel_Laravel 5_Eloquent - Fatal编程技术网

如何在Laravel中使用eloquent从子表中获取值?

如何在Laravel中使用eloquent从子表中获取值?,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,我有两个表:users和profile。 用户可以有一个或多个配置文件。我想访问这两个表的组合数据:用户表中的“ID”是配置文件表中的外键 用户模型: class User extends Authenticatable { use Notifiable; protected $fillable = [ 'first_name','last_name', 'email', 'password','phone','user_type', ]; protected

我有两个表:users和profile。 用户可以有一个或多个配置文件。我想访问这两个表的组合数据:用户表中的“ID”是配置文件表中的外键

用户模型:

class User extends Authenticatable
{
   use Notifiable;

   protected $fillable = [
    'first_name','last_name', 'email', 'password','phone','user_type',
   ];

   protected $hidden = [
    'password', 'remember_token',
   ];

   public function profile()
   {
       return $this->hasMany(profile::class);
   }
}
配置文件模型为:

class profile extends Model
{
   protected $fillable = [
                    'id','relationship_status','dob','height',
                    'weight','primary_language'
                  ];
   protected $primaryKey = 'profile_id';

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

像这样更改您的用户模型配置文件关系

用户模型

public function profile()
{
    return $this->hasOne(Profile::class); //assuming your user has single profile
}
剖面模型

class Profile extends Model
{
   protected $fillable = [
                         'id', 'user_id', 'relationship_status','dob','height',
                         'weight','primary_language'
                         ];

   //add user_id field in profiles table
   //protected $primaryKey = 'profile_id'; //no need of this, because you have id field in profiles table

   public function user()
   {
     return $this->belongsTo(User::class);
   }
}
之后,您可以像这样获取数据

$user = User::find(2);
dd($user);
dd($user->profile)
获取多个用户详细信息时,请使用即时加载

$users = User::with('profile')->get();

foreach($users as $user){
   dd($user->profile)
}

检查详细信息

您是否可以通过示例详细说明您想要什么用户
拥有多个
配置文件或
拥有一个
配置文件?从您的问题中,我发现您的数据库结构id不正确。配置文件表中的用户id在哪里?我在配置文件表中使用了相同的字段名,id