laravel BadMethodCallException 带有消息“调用未定义的方法 Illuminate\Database\Query\Builder::toArray()”

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

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'

phplaravellaravel-5laravel-5.2

提问by Hashmatullah Noorzai

I am working along with @Jeffrey_way series of Laracasts Many to Many Relations (With Tags)

我正在与@Jeffrey_way 系列的 Laracasts 多对多关系(带标签)一起工作

Below is the code I have written in CMD using Laravel Tinker:

下面是我使用 Laravel Tinker 在 CMD 中编写的代码:

After executing the last line of code ($article->tags()->toArray();

执行最后一行代码后($article->tags()->toArray();

Although everything seems to be OK with my code but still I get following error:

虽然我的代码似乎一切正常,但我仍然收到以下错误:

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'

any help would be much appreciated :)

任何帮助将非常感激 :)

采纳答案by YigitOzkavci

If you want to actually "get" relational data, you don't put parenthesis arount tags. This will work just fine:

如果您想真正“获取”关系数据,则不要将括号放在tags. 这将工作得很好:

$article->tags->toArray();

You put parenthesis when you need to "query" to that collection (Ex. sync, save, attach).

当您需要“查询”到该集合(例如同步、保存、附加)时,您可以放置​​括号。

Reference: https://laravel.com/docs/5.1/eloquent-relationships#many-to-many

参考:https: //laravel.com/docs/5.1/eloquent-relationships#many-to-many

回答by delatbabel

Try this instead:

试试这个:

$article->tags()->all()->toArray();

Underlying the tags()is probably a Query\Builderobject which represents a query that has not yet run. Instead you need a Collection object which is a query that has run, on which to call toArray(). ->all()is one such call that converts a query builder into a collection by actually running the query.

底层tags()可能是一个Query\Builder表示尚未运行的查询的对象。相反,您需要一个 Collection 对象,它是一个已运行的查询,在该对象上调用toArray(). ->all()就是这样一种调用,它通过实际运行查询将查询构建器转换为集合。

回答by AlmostPitt

I had the same problem and solved it by adding get()

我遇到了同样的问题并通过添加解决了它 get()

For example:

例如:

$article->tags()->get()->toArray();

Hope this helps someone :)

希望这对某人有所帮助:)