本文介绍了Laravel在数组错误上调用成员函数toArray()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以消除我因此错误而遇到的一些困惑.所以这是我的代码. (注意)用户模型与Image具有hasMany关系

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 = User::with('profile')->whereUsername($username)->firstOrFail();

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

    dd($user->toArray());

我的困惑是dd($ user-> toArray());工作完美.但是当我尝试这个dd($ images-> toArray())时,我得到了对数组上成员函数toArray()的调用.这已经使我丧命了一段时间. $ user和$ images都是对象,但是toArray()仅适用于$ user.同样,$ images [0]-> 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.

推荐答案

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

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

这篇关于Laravel在数组错误上调用成员函数toArray()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:42