新手問題在這里,我有一個員工/個人資料模型,其中我有一個引導功能來創建一個創建員工模型的用戶。
public static function boot()
{
parent::boot();
static::created(function($model)
{
$User = new \App\Models\User;
$User->id = $model->id;
$User->name = $model->first_name.' '.$model->last_name;
$User->email = $model->work_email;
$User->save();
});
在檢查資料庫時,我注意到它沒有選擇員工 ID (UUID) 并將相同的 ID 保存為用戶 ID
$User->id = $model->id;
我在這里做錯了什么?
我發現我可以在保存后通過添加來更新它
public static function boot()
{
parent::boot();
static::created(function($model)
{
$User = new \App\Models\User;
$User->id = $model->id;
$User->name = $model->first_name.' '.$model->last_name;
$User->email = $model->work_email;
$User->save();
$User->id = $model->id;
$User->save();
});
}
有沒有辦法在不節省兩次的情況下做到這一點?
uj5u.com熱心網友回復:
您從根本上誤解了應該如何創建資料庫關系。您不會通過給它們相同的 ID 來表明兩個條目是相關的。
您可以通過在遷移中的兩個表之間創建外鍵來做到這一點:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->foreignId('employee_id')->constrained('employees');
$table->string('name');
$table->string('email');
});
}
然后在您的 ORM 中創建關系。
class User extends Authenticatable {
public function employee() {
return $this->belongsTo(Employee::class);
}
}
class Employee extends Model {
public function user() {
return $this->hasOne(User::class);
}
}
然后您的事件處理程式如下所示:
public static function boot()
{
parent::boot();
static::created(function ($model) {
$u = User::make([
'name' => $model->first_name . ' ' . $model->last_name,
'email' => $model->work_email,
]);
$u->employee = $model;
$u->save();
});
}
現在您已經將用戶與員工相關聯,因此您可以執行以下操作:
$user = User::find(123);
echo $user->employee->first_name;
uj5u.com熱心網友回復:
嘗試forceCreate(...)改用。
保存新模型并回傳實體。允許批量分配。
\App\Models\User::forceCreate([
"id" => $model->id,
"name" => $model->first_name . ' ' . $model->last_name,
"email" => $model->work_email,
]);
附錄
或者,您可以使用forceFill(...)
用一組屬性填充模型。強制質量分配。
(new \App\Models\User)->forceFill([
"id" => $model->id,
"name" => $model->first_name . ' ' . $model->last_name,
"email" => $model->work_email,
])->save();
uj5u.com熱心網友回復:
如果您創建一個新用戶,則不應添加id. 如果要更新現有用戶,則應使用例如find而不是創建新模型物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/423109.html
標籤:
