我有兩個具有 1:1 關系的模型,分別命名為User和UserProfile。
class User extends Model
{
protected $with = ['profile'];
public function profile(): HasOne
{
return $this->hasOne(UserProfile::class);
}
}
class UserProfile extends Model
{
protected $touches = ['user'];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
在我用這些模型創建新記錄并將它們關聯之后,我應該呼叫該refresh()方法(根據Laravel 的 Docs)以重新加載模型及其所有關系。但不知何故,這不起作用。
$user = new User($userData);
$profile = new UserProfile($profileData);
$user->save();
$user->profile()->save($profile);
$user->refresh();
$user->relationLoaded('profile'); // <-- This will be false
// $user = User::find($user->id); // <-- This will work
// $user->load('profile'); // <-- This will work
return response()->json(['data' => $user], 201);
因為組態檔關系沒有加載,它不會被序列化,因此它不會出現在 JSON 回應中。
我想知道我做錯了什么還是一個錯誤?
uj5u.com熱心網友回復:
海事組織,這是預期的行為。如果您檢查代碼,則永遠不會profile在物件中加載關系,$user因此它解釋了原因:
$user->relationLoaded('profile'); // false
如果您將關系作為屬性訪問(在更新組態檔之后),它將獲取關系:
$profileImage = $user->profile; // not null
如果您已經加載了關系,也會發生同樣的情況:
$user = new User($userData);
$user->save();
$currentProfile = $user->profile; // null
$profile = new UserProfile($profileData);
$user->profile()->save($profile);
$user->refresh();
$currentProfile = $user->profile; // not null
從檔案:
save 和 saveMany 方法將持久化給定的模型實體,但不會將新持久化的模型添加到已加載到父模型上的任何記憶體關系中。如果您打算在使用 save 或 saveMany 方法后訪問關系,您可能希望使用 refresh 方法重新加載模型及其關系:(...)
uj5u.com熱心網友回復:
Laravel Doc 忘記提到必須為該技巧預先加載關系。
$trick = $post->comments;
$post->comments()->save($comment);
$post->refresh();
保存方法不加載任何內容。您可以在保存后使用加載方法。
$user->profile()->save($profile);
$user->load('profile');
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422702.html
標籤:
上一篇:Laravel資料未從控制器更新
下一篇:播種以使用強制性和隨機資料填充表
