【问题标题】:How to get specific columns from relation table in laravel?如何从laravel中的关系表中获取特定列?
【发布时间】:2021-01-28 10:18:50
【问题描述】:

我正在尝试从关系表中获取特定的列数据,但它给了我 null

$allConsignments = Consignment::query();
$allConsignments->select(['id','customer_reference'])->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get();

当我不使用 select() 时,它会提供正确的数据。

喜欢这个

$allConsignments = Consignment::query();
$allConsignments->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get()

它正在工作,但我还需要 Consignment 表中的特定列。可能是什么原因?

【问题讨论】:

  • 删除select(),在get()上查询get(['id','customer_reference'])
  • 我试过了,但是不行
  • 为这些表提供相关模型和迁移

标签: laravel laravel-5 eloquent


【解决方案1】:

你也可以这样做。

$allConsignments = Consignment::query();

$allConsignments::with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get(['id','customer_reference']);

【讨论】:

    【解决方案2】:

    实际上,我还需要从关系所基于的表中选择外键列。例如,在我的情况下,我在寄售表中有customer_id,所以应该是这样的

    $allConsignments = Consignment::query();
    $allConsignments->select('id','customer_reference','customer_id')->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get();
    

    我也需要选择customer_id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2021-12-04
      • 2020-06-02
      • 2021-01-20
      • 2021-08-25
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多