简体   繁体   English

Laravel:将Eloquent集合转换为Array而不转换元素

[英]Laravel: Convert Eloquent collection to Array without converting elements

Is there a (simple) way to convert an Eloquent Collection to an actual array without converting the elements themselves? 有没有(简单)方法将Eloquent Collection转换为实际数组而不转换元素本身?

I get in trouble when I try to pass the collection into a php method like array_rand($collection) . 当我尝试将集合传递给像array_rand($collection)这样的php方法时,我遇到了麻烦。 This gives me the error: array_rand() expects parameter 1 to be array, object given . 这给了我错误: array_rand() expects parameter 1 to be array, object given

I worked around this by using $collection->shuffle()->first(); 我通过使用$collection->shuffle()->first();来解决这个问题$collection->shuffle()->first(); which works fine and of course I could loop over the collection and push all in an array, but just out of curiosity I wonder if I'm overlooking something. 哪个工作正常,当然我可以循环收集并推送所有数组,但出于好奇我想知道我是否忽略了一些东西。

Update / Conclusion 更新/结论

There seems to be a difference between the all method on a Illuminate\\Support\\Collection and a Illuminate\\Database\\Eloquent\\Collection . Illuminate\\Support\\Collection上的all方法和Illuminate\\Database\\Eloquent\\Collection之间似乎有区别。 The all on an Eloquent Collection returns a Support Collection and the Support Collection returns an Array. Eloquent Collection上的all返回支持集合,Support Collection返回一个Array。

So to get an Array of Eloquent models you need to use SomeModel::all()->all(); 因此,要获得一个SomeModel::all()->all();模型数组,您需要使用SomeModel::all()->all();

My first thought was $collection->toArray() but that also converts the Eloquent models to arrays. 我的第一个想法是$collection->toArray()但它也将Eloquent模型转换为数组。 But the docs say that $collection->all() should avoid that. 但是文档$collection->all()应该避免这种情况。

toArray also converts all of the collection's nested objects to an array. toArray还将所有集合的嵌套对象转换为数组。 If you want to get the raw underlying array, use the all method instead. 如果要获取原始基础数组,请改用all方法。

You can use the all collection helper: 您可以使用all collection helper:

The all method returns the underlying array represented by the collection: all方法返回集合表示的底层数组:

collect([1, 2, 3])->all();

// [1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM