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

Eloquent query problem using with() function for model relationship eager loading

如何在 Laravel 中编写此 eloquent 查询,以便它急切地加载 with() 此示例中 [=27] 之间的关系模型=]User 模型和 Profile 模型?我试图避免 2 个单独的查询。

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

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

该集合正在正确返回用户详细信息。但它显示 profile 关系为空。

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

我相信我已经正确设置了 User 模型和 Profile 所需的关系。

User.php

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

AuthorProfile.php

public function user()
{
    return $this->belongsTo('App\User');
}
$users = User::with('profile')->find($id);

假设 AuthorProfile 模型 table 你有用户 ID 的记录应该没问题。

无论你怎么写:

I was trying to avoid 2 separate queries.

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

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

另外代替:

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

你应该使用:

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

因为你希望这里是单用户。

您的模型应该像个人资料 this.The User_id 和用户 table

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