php Laravel 在数组错误时调用成员函数 toArray()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26536518/
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-08-25 22:57:02  来源:igfitidea点击:

Laravel Call to a member function toArray() on array Error

phpmacoslaravel

提问by jhamPac

I was hoping someone could possibly clear up a little confusion I've been having with this Error. So here is my code. (note) the User model has a hasMany relationship to Image

我希望有人可以解决我一直对这个错误产生的一些困惑。所以这是我的代码。(注意) User 模型与 Image 有 hasMany 关系

    $user = User::with('profile')->whereUsername($username)->firstOrFail();

    $images = $user->images->all();

    dd($user->toArray());

My confusion is dd($user->toArray()); works perfectly fine. But when I try this dd($images->toArray()) I get a Call to a member function toArray() on array. This has been killing me for a while. $user and $images are both objects but toArray() only works on $user. Also, $images[0]->toArray() works fine too so that just adds to the confusion.

我的困惑是 dd($user->toArray()); 工作得很好。但是当我尝试这个 dd($images->toArray()) 时,我得到了一个对数组成员函数 toArray() 的调用。这已经杀了我一段时间了。$user 和 $images 都是对象,但 toArray() 仅适用于 $user。此外, $images[0]->toArray() 也能正常工作,因此只会增加混乱。

回答by geoandri

I think this happens because $images is a collection of objects not an object like $user. Check querying-relationsin the documentation the red area in the end of that section. That explains why $images[0]->toArray() works fine.

我认为这是因为 $images 是对象的集合,而不是像 $user 这样的对象。检查文档中该部分末尾的红色区域中的查询关系。这解释了为什么 $images[0]->toArray() 工作正常。