Php 具有关系的查询模型字段

Php 具有关系的查询模型字段,php,laravel,eloquent,laravel-relations,Php,Laravel,Eloquent,Laravel Relations,我有两个模型,用户和枚举器。我想搜索枚举器模型中的某些列及其在用户模型中的关系。这就是我所拥有的 Enumerator::with(['user' => function($query) { $query->select('id', 'first_name', 'last_name', 'email'); }])->get(['first_name', 'unique_id']); 统计员 唯一标识 使用者 名字 我想编写一个查询,该查询将获取同一集合中

我有两个模型,用户和枚举器。我想搜索枚举器模型中的某些列及其在用户模型中的关系。这就是我所拥有的

Enumerator::with(['user' => function($query) {
       $query->select('id', 'first_name', 'last_name', 'email');
}])->get(['first_name', 'unique_id']);
统计员

  • 唯一标识
使用者

  • 名字
我想编写一个查询,该查询将获取同一集合中的唯一\u id和第一个\u名称

这就是我所拥有的

Enumerator::with(['user' => function($query) {
       $query->select('id', 'first_name', 'last_name', 'email');
}])->get(['first_name', 'unique_id']);

我该怎么做呢?

如果您想在同一个集合中获得多个表列,最好在这里这样使用

$joinTableName = (new App\User())->getTable();
$fromTableName = (new App\Enumerator())->getTable();
$foreignKey = "enumerators_id"; //user table set foreign key
$localKey = "id";  //enumerators table column local key

$selectColumns = [
    "{$joinTableName}.first_name",
    "{$fromTableName}.unique_id",
];

$a = App\Enumerator::select($selectColumns)
    ->join(
        $joinTableName,
        "{$joinTableName}.{$foreignKey}",
        '=',
        "{$fromTableName}.{$localKey}"
)->get();

dd($a);