【问题标题】:Laravel Eloquent Collection returned as objectLaravel Eloquent Collection 作为对象返回
【发布时间】:2021-06-03 00:08:06
【问题描述】:

为什么我的 laravel eloquent 查询返回一个对象?返回的数据不应该是一个雄辩的集合的形式吗?这应该允许我使用拼接方法。

有人可以向我解释为什么 $location tier 1 中的数据被视为一个对象吗?如果有什么不应该是一个包含对象的数组? [对象,对象],我正在尝试通过索引将对象插入到此数组中

The data contained within $location tier 1 is
[{"id":1,"name":"school","lat":0,"lng":0,"enable_audit":0,"x_axis":0,"y_axis":0,"z_axis":0,"service_provider_id":0,"client_id":313,"description":"school","order":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","location_id":1,"parent_id":0},{"id":4,"name":"school","lat":0,"lng":0,"enable_audit":0,"x_axis":0,"y_axis":0,"z_axis":0,"service_provider_id":0,"client_id":313,"description":"school","order":2,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","location_id":1,"parent_id":0}]

 $location_tier_1 = LocationTier1::where('location_id','=',$location_id)->orderby('id')->get();
 array_splice($location_tier_1,$i+1,0,$value);

【问题讨论】:

  • Eloquent 总是返回一个名为 Collection 的对象,尝试:$location_tier_1= $location_tier_1->toArray(); array_splice($location_tier_1,$i+1,0,$value); 或尝试拼接它。 $location_tier_1->splice($i+1,0,$value);
  • @Mariano 那么我如何将它转换回一个集合?我仍然需要使用 $location 中的属性,例如 $location->id
  • 好吧,试试 Laravel @Yeo Bryan 的 ->splice() 方法
  • @Mariano 使用拼接插入到集合中?我做到了,它反映了那里的错误

标签: php laravel eloquent


【解决方案1】:

你可以使用 Laravel 收集方法

$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
// [3, 4, 5]
$collection->all();
// [1, 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2018-07-02
    相关资源
    最近更新 更多