如何在Laravel中使用雄辩的方式从子表中获取价值?

时间:2018-07-10 03:37:38

标签: laravel laravel-5 eloquent

我有两个表:用户和个人资料。 用户可以具有一个或多个配置文件。我想访问两个表的组合数据:用户表中的“ 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');
   }
}

1 个答案:

答案 0 :(得分:2)

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

用户模型

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)
}

查看详细信息https://laravel.com/docs/5.6/eloquent-relationships#one-to-one