Laravel Eloquent 如何通过关系函数将主表列值传递给

分享于2022年07月17日 laravel php 问答
【问题标题】:Laravel Eloquent 如何通过关系函数将主表列值传递给(Laravel Eloquent how pass main table column value to with relationship function)
【发布时间】:2022-07-07 00:28:11
【问题描述】:

我正在使用 eloquent 查询一个数据库条目及其对应关系。问题是我需要将用户名传递到关系查询中,如下所示:

$users = User::with(['posts' => function($query)
{
    $query->select('id, title, concat(users.name, ' ' ,title) as title_with_name');

}])->get();

结果:

[
  ...
  {
    "id" => 1,
    "name" => "admin",
    "email" => "admin@admin.com",
    ...
    "posts" => [
      {
        "id" => 1,
        "title" => "first post",
        "title_with_name" => "jack first post"
      },
      {
        "id" => 2,
        "title" => "second post",
        "title_with_name" => "jack second post"
      }
    ]
  }
]


【解决方案1】:

您需要使用 DB Facade 将原始查询传递给 select 方法。

$users = User::with(['posts' => function($query)
{
    $query->select(DB::raw('id, title, concat(users.name, ' ' ,title) as title_with_name'));

}])->get();