【问题标题】:How to get value from child table using eloquent in Laravel?如何在 Laravel 中使用 eloquent 从子表中获取价值?
【发布时间】:2018-07-10 14:05:48
【问题描述】:

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

【问题讨论】:

  • 您能否通过示例详细说明您想要什么
  • 用户hasMany 个人资料或hasOne 个人资料?
  • 从你的问题我发现你的数据库结构 id 不正确。个人资料表中的 user_id 在哪里?
  • 我在配置文件表中使用了相同的字段名称,ID

标签: laravel laravel-5 eloquent


【解决方案1】:

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

用户模型

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多