【问题标题】:Select specific columns of table and relation in laravel在laravel中选择表和关系的特定列
【发布时间】:2018-06-23 07:04:21
【问题描述】:

假设我有一个模型User 和另一个模型Employee

现在我只想提取 Employee 模型的一些字段,例如 salary, id, emp_id 以及 User 模型的一些列,例如 name,id。 p>

$employee = Employee::with('user:id,name')
             ->where('department', $request->department)
             ->get(['id', 'emp_id', 'salary']);

当我执行此操作时,它将返回 id,emp_id,salary 数据,但对于 user:name,id 它将返回 null

如何在 get() 中指定 user:id,name

【问题讨论】:

    标签: sql laravel-5 eloquent


    【解决方案1】:

    您可以加载完整模型或仅加载其中的某些字段。要仅加载某些字段,请使用 select()。它也适用于关系急切加载查询:

    $employees = Employee::with(['user' => function ($query) {
            $query->select(['id', 'employee_id', 'name']);
        }])
        ->where('department', $request->department)
        ->select(['id', 'emp_id', 'salary'])
        ->get();
    

    【讨论】:

    • 这仍然无法正常工作。它给出了错误提示 user.name column not found
    • @Raj 你想要的输出到底是什么?包含五列的数组还是仅加载了这五个属性的模型?
    • 我需要从中返回一个可以在视图中使用的模型
    • 这返回了最后的选择列:['id', 'emp_id', 'salary'] 但对于关系用户,它返回 null:user:null
    • 您可能需要将employee_id 添加到用户的选择列表中,否则 Eloquent 无法匹配它们。在我的答案中修复它...
    【解决方案2】:

    使用 Query bulider 中的 select() 方法:

    $employee = Employee::with('user')   // or users <---
                        ->select(['id', 'emp_id', 'salary', 'users.id AS user_id', 'users.name AS username'])
                        ->where('department', $request->department)
                        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-22
      • 2019-09-28
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多