gpt4 book ai didi

mysql - 使用with()函数进行模型关系预加载的 Eloquent 查询问题

转载 作者:行者123 更新时间:2023-11-29 06:39:34 25 4
gpt4 key购买 nike

如何在 Laravel 中编写这个 Eloquent 查询,以便它立即加载 with() 本例中 User 模型和 Profile 之间的关系模型强>模型?我试图避免两个单独的查询。

我觉得我已经很接近了,但有些地方不太对劲。

$author = User::where('id', $id)->with('profile')->get();

集合正确返回用户详细信息。但它显示个人资料关系为空。

  #relations: array:1 [▼
"profile" => null
]

我相信我已经正确设置了用户模型和个人资料所需的关系。

用户.php

public function profile()
{
return $this->hasOne('App\AuthorProfile', 'user_id');
}

作者文件.php

public function user()
{
return $this->belongsTo('App\User');
}

最佳答案

假设对于 AuthorProfile 模型表,您有用户 ID 的记录,应该没问题。

不管你怎么写:

I was trying to avoid 2 separate queries.

嗯,这不是真的,如果你只有一条记录,急切加载根本不会帮助你。在这种情况下,将执行 2 个查询 - 无论您是否使用预加载。

如果您有多个用户,并且您想为每个用户加载配置文件,那么预加载会有所帮助,但如果您只有一条记录,则不会改变任何内容。

另外代替:

$author = User::where('id', $id)->with('profile')->get();

你应该使用:

$author = User::with('profile')->find($id);

因为您期望这里是单用户。

关于mysql - 使用with()函数进行模型关系预加载的 Eloquent 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52372922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com