如何刷新Laravel中新建模型的所有关系?

How to refresh all relations of a newly created model in Laravel?

我有两个具有 1:1 关系的模型,分别名为 UserUserProfile

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's 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 响应中。

我想知道我是不是做错了什么或者是一个错误?

Imo,这是预期的行为。如果你检查你的代码,你永远不会在你的 $user 对象中加载 profile 关系,所以它解释了原因:

$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

来自文档:

The save and saveMany methods will persist the given model instances, but will not add the newly persisted models to any in-memory relationships that are already loaded onto the parent model. If you plan on accessing the relationship after using the save or saveMany methods, you may wish to use the refresh method to reload the model and its relationships: (...)

Laravel Doc 忘记提到关系必须预先加载才能使用该技巧。

$trick = $post->comments;
$post->comments()->save($comment);
$post->refresh();

save 方法不加载任何内容。您可以在保存后使用 load 方法。

$user->profile()->save($profile);
$user->load('profile');