laravel Eloquent ORM 单项集合作为数组返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19648722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:36:45  来源:igfitidea点击:

Eloquent ORM single item collection return as array

phparrayslaravellaravel-4eloquent

提问by KernelCurry

Code: $account->deals

代码: $account->deals

This like returns an object or an array of objects.

这就像返回一个对象或一组对象。

object: {deal}

目的: {deal}

Array of Objects: [{deal}, {deal}, {deal}]

对象数组: [{deal}, {deal}, {deal}]

Is there a way to force the call to return an "array of objects" even if it is only returning one object?

有没有办法强制调用返回“对象数组”,即使它只返回一个对象?

To clarify, I do not want to use a foreach, is_array(), count(), etc...

为了澄清,我不想使用foreachis_array()count()等...

this is the end product I am looking to have work: $deals = array_merge($account->deals, $user->deals);even when Eloquent only returns one object.

这是我希望工作的最终产品:$deals = array_merge($account->deals, $user->deals);即使 Eloquent 只返回一个对象。

回答by KernelCurry

Figured it out!

弄清楚了!

$deals = array_merge($account->deals->all(), $user->deals->all());

$deals = array_merge($account->deals->all(), $user->deals->all());

Hope this helps someone out in the fugure

希望这可以帮助某人在未来

回答by cheelahim

Collection object in laravel has method toArray() to represent collection of objects as multi-dimentional array (array of arrays). Try this:

laravel 中的集合对象有方法 toArray() 将对象集合表示为多维数组(数组数组)。尝试这个:

$deals = $account->deals->toArray();