gpt4 book ai didi

laravel - 如何在 Laravel 中使用 Eloquent 从子表中获取值?

转载 作者:行者123 更新时间:2023-12-05 05:15:48 25 4
gpt4 key购买 nike

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

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

关于laravel - 如何在 Laravel 中使用 Eloquent 从子表中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com