[英]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.