[英]How to retrieve value from another database table in laravel?
I have two table named users
and profiles
.In users
table its have a column named id
and in profiles
table its have a column named userID
.Now i want when users
table increasing id
then userID
automatic fill up respectively.我有两个名为
users
和profiles
表。在users
表中有一个名为id
的列,在profiles
表中有一个名为userID
的列。现在我希望当users
表增加id
然后userID
分别自动填充。
If anyone create profile then the userID
column auto fill up according to the login users
table id
.How can i do that?如果有人创建配置文件,则
userID
列会根据登录users
表id
自动填充。我该怎么做?
User Model:用户模型:
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');
}
}
Profile Model:型材型号:
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');
}
}
But when i add a profile with an user then in profiles
table userID
column is blank.But it should be fill up according to login id of the users
table.但是当我添加一个带有用户的配置文件时,在
profiles
表中userID
列是空白的。但它应该根据users
表的登录 ID 填写。
By the way i am new in Laravel.顺便说一下,我是 Laravel 的新手。 Thanks.
谢谢。
Get the user id like this像这样获取用户ID
$id = Auth::id();
and then assign this value to user property in profile like然后将此值分配给配置文件中的用户属性,例如
$profile->userID = $id
When saving a profile, add a user to it with:保存配置文件时,向其中添加用户:
$profile->userHave = $user
A couple of things:几件事:
Your Profile
model does not need userID
to be fillable.您的
Profile
模型不需要userID
即可填写。 This is filled by your relation so really shouldn't be fillable.这是由您的关系填充的,因此真的不应该填充。
The relation is named a bit weirdly.这种关系的命名有点奇怪。 It should really be the name of the attribute that you expect to use to fetch the relation.
它实际上应该是您希望用于获取关系的属性的名称。 For instance, I would call the user relation in your profile just
user
:例如,我会将您个人资料中的用户关系称为
user
:
public function user() { return $this->belongsTo('App\\User','userID'); }
With this, you would add a user to a profile with the following:有了这个,您将使用以下内容将用户添加到配置文件中:
$profile->user = $user;
Lastly, think about whether you actually need a profile model .最后,考虑一下您是否真的需要配置文件模型。
All the attributes in your profile model are attributes of the user.您的配置文件模型中的所有属性都是用户的属性。 If you plan on having a profile for every user, you have no reason to have a different model for a profile.
如果您计划为每个用户拥有一个配置文件,则没有理由为配置文件使用不同的模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.