[英]How to retrieve value from another database table in laravel?
我有两个名为users
和profiles
表。在users
表中有一个名为id
的列,在profiles
表中有一个名为userID
的列。现在我希望当users
表增加id
然后userID
分别自动填充。
如果有人创建配置文件,则userID
列会根据登录users
表id
自动填充。我该怎么做?
用户模型:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profileHave(){
return $this->hasOne('App\Profile','userID');
}
}
型材型号:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["userID","firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function userHave(){
return $this->belongsTo('App\User','userID');
}
}
但是当我添加一个带有用户的配置文件时,在profiles
表中userID
列是空白的。但它应该根据users
表的登录 ID 填写。
顺便说一下,我是 Laravel 的新手。 谢谢。
像这样获取用户ID
$id = Auth::id();
然后将此值分配给配置文件中的用户属性,例如
$profile->userID = $id
保存配置文件时,向其中添加用户:
$profile->userHave = $user
几件事:
您的Profile
模型不需要userID
即可填写。 这是由您的关系填充的,因此真的不应该填充。
这种关系的命名有点奇怪。 它实际上应该是您希望用于获取关系的属性的名称。 例如,我会将您个人资料中的用户关系称为user
:
public function user() { return $this->belongsTo('App\\User','userID'); }
有了这个,您将使用以下内容将用户添加到配置文件中:
$profile->user = $user;
最后,考虑一下您是否真的需要配置文件模型。
您的配置文件模型中的所有属性都是用户的属性。 如果您计划为每个用户拥有一个配置文件,则没有理由为配置文件使用不同的模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.