【问题标题】:Laravel Eloquent eager Loading and Retrieving Values From the ArrayLaravel Eloquent 急切地从数组中加载和检索值
【发布时间】:2018-09-05 03:30:38
【问题描述】:

使用 Laravel 的 Eloquent 和急切加载如何检索 built_load_cost 数组和 built_load_revenue 数组中的值?

```

  array:11 [▼
  "id" => 5
  "created_at" => "2018-03-24 00:19:52"
  "updated_at" => "2018-03-24 00:20:14"
  "load_number" => 1
  "dispatcher_id" => 3
  "carrier_id" => 826097731
  "customer_id" => 1
  "ip" => "127.0.0.1"
  "deleted_at" => null
  "built_load_cost" => array:6 [▼
    "id" => 4
    "created_at" => "2018-03-26 19:59:34"
    "updated_at" => "2018-03-26 19:59:34"
    "line_haul" => "100.00"
    "extra_pickups" => "0.00"
    "built_load_id" => 5
  ]
  "built_load_revenue" => array:6 [▼
    "id" => 4
    "created_at" => "2018-03-26 19:59:43"
    "updated_at" => "2018-03-26 19:59:43"
    "line_haul" => "90.00"
    "extra_pickups" => "0.00"
    "built_load_id" => 5
  ]
]

```

【问题讨论】:

  • 嗯,和其他数组一样。 $arr[index][prop] 在你的情况下。也许我不明白这个问题。
  • 是的,我就是这么想的。除了它返回null。我有这个查询: $load = BuiltLoad::with('builtLoadCost')->with('builtLoadRevenue')->where('dispatcher_id', '=', $dispatcher_id)->where('id', '= ', $id)->first();然后我用这个: $line_haul = $load['built_load_revenue']['line_haul']; ...返回null。无法弄清楚为什么我得到 null。我应该得到 90
  • 你如何检索你得到空的数据?
  • @jedrzej.kurylo 我能够检索 load-number 和 customer_id 的值以及主数组的所有值,而不是来自我最初问题中提到的 2 个数组
  • 发布代码,用于检索给您 null 的数据

标签: laravel eloquent


【解决方案1】:

通过 eloquent 模型访问 value 时,使用camelCase,第一个小写字母:

$load->builtLoadCost->line_haul
$load['builtLoadCost']['line_haul']

如果将eloquent模型转为数组,使用snake_case访问关系:

$load->toArray()['built_load_revenue']['line_haul']

另请参阅:Laravel “with” changes variable case to snake case

【讨论】:

  • 谢谢。这 $load->toArray()['built_load_revenue']['line_haul'] 有效。仍然不确定为什么我的原始代码不起作用而您的代码有效。我认为我使用的 eloquent 模型正在返回一个数组。
  • eloquent 模型不是数组,但是因为重载可以当作数组使用,->toArray() 用于将 eloquent 模型序列化为数组
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 2016-08-17
  • 2018-03-29
  • 2013-06-10
  • 2019-07-08
  • 2012-12-26
  • 2017-09-30
  • 1970-01-01
相关资源
最近更新 更多