【问题标题】:Laravel eager loading specific columns errorLaravel 急切加载特定列错误
【发布时间】:2020-01-13 23:07:10
【问题描述】:

我有自定义代码,我必须从关系数据中获取特定列:

$jobs = Job::with('user:id, name')
           ->where('type', 0)
           ->where('status', 1)
           ->orderBy('updated_at', 'DESC')
           ->get();

当我运行此代码时,Laravel 返回错误消息:

SQLSTATE[42S22]:未找到列:1054 中的未知列“名称” '字段列表'

我该如何解决这个错误?

【问题讨论】:

  • 用户表中有名称字段吗?
  • 这是我的$fillable 变量值:protected $fillable = ['name', 'email', 'password', 'phone', 'status'];
  • Unknown column ' name',有空格' name'
  • @AndreasHunter 空间是个问题,所以只删除空间。

标签: laravel eloquent relationship laravel-6


【解决方案1】:

在这段代码中有空格with('user:id, name')。问题是空间。
试试这个

$jobs = Job::with('user:id,name')
    ->where('type', 0)
    ->where('status', 1)
    ->orderBy('updated_at', 'DESC')
    ->get();

【讨论】:

    【解决方案2】:

    可以通过在 with() 中传递一个闭包函数作为数组的第二个索引来完成,例如

    $jobs = Job::with(['user' =>  function($q){
                    $q->select('id','name');
                }])->where('type', 0)
                   ->where('status', 1)
                   ->orderBy('updated_at', 'DESC')
                   ->get();
    

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 1970-01-01
      • 2015-05-08
      • 2021-01-21
      • 2018-03-18
      • 1970-01-01
      • 2014-08-13
      • 2021-04-23
      • 2018-10-15
      相关资源
      最近更新 更多