如何使用 belongsToMany 正确 select 特定列?

How to properly select specific columns using belongsToMany?

我有包含以下关系的 UserModel

public function patients()
{
    return $this->belongsToMany(User::class, 'invites', 'tenant_id', 'user_id');
}

这个关系 returns 所有 patients 关联到当前登录的用户,所以如果我调用这个:

auth()->user()->patients()->toSql();

它returns这个查询:

select
    *
from
    `users`
inner join
    `invites` on `users`.`id` = `invites`.`user_id`
where
    `invites`.`tenant_id` = ?
    and `users`.`deleted_at` is null

这是正确的。但我想使用这样的模型:

$userModel = new App\Models\Boilerplate\User();
return $userModel::with('patients')->select([
    'users.id',
    'email',
    'last_name',
    'first_name',
    'active',
    'users.created_at',
    'last_login',
]);

如果我打印最后一个查询,我得到这个:

select
    `users`.`id`,
    `email`,
    `last_name`,
    `first_name`,
    `active`,
    `users`.`created_at`,
    `last_login`
from
    `users`
where
    `users`.`deleted_at` is null

这与第一个运行正常的查询完全不同。

如果我用$userModel结果当然是错误的,它returns所有用户可用table,但结果必须和[=19=一样].

我做错了什么?

  1. 主要 select() 必须包含来自 usersid
  2. 子查询 select() 必须包含来自 patients
  3. user_id
$userModel::select('id', 'and_other_user_columns')
    ->with(['patients' => function ($query) {
    $query->select('user_id', 'and_other_patient_columns');
}])
    ->get();

您可以使用 with 方法。但是您必须在查询中包含患者 ID。

return $userModel::with('patients:id, email, last_name, first_name, active, last_login')->select(['id','created_at'])->get();