问题描述
我遇到了我认为很简单的事情,我只是想多了。我在 Tinker 会话中运行以下命令,它按预期工作:
$game = Games::find(1);
[!] Aliasing 'Games' to 'App\Models\Games' for this Tinker session.
=> App\Models\Games {#4386
id: 1,user_id: 1,title: "Test Game",description: "This is a test of the game function",max_players: 8,deck: "default",type: "Golf",privacy: "Public",current_player: null,status: "pending",deleted_at: null,created_at: "2020-12-18 22:02:17",updated_at: "2020-12-18 22:02:17",}
>>> $game->players()->get();
=> Illuminate\Database\Eloquent\Collection {#4322
all: [
App\Models\User {#4384
id: 1,name: "mark",email: "test@test.com",username: "user",role: null,email_verified_at: null,created_at: "2020-12-18 22:02:08",updated_at: "2020-12-18 22:02:08",pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4168
games_id: 1,},],}
我基本上已经在我的控制器中放置了完全相同的代码来提取游戏中的玩家列表:
$game = Games::find($game);
$players = $game->players()->get();
当我到达路线时我得到了这个:
Method Illuminate\Database\Eloquent\Collection::players does not exist.
我很困惑,如果它在 Tinker 中运行良好,为什么它在控制器中不起作用。
感谢您的帮助!
解决方法
$ pdffonts pgf_backend.pdf
name type emb sub uni prob object ID
---------------------------- ----------------- --- --- --- ---- ---------
KECVVY+ArialMT CID TrueType yes yes yes 7 0
EFAAMX+CMR12 Type 1C yes yes yes 8 0
EHYQVR+CMSY8 Type 1C yes yes yes 9 0
UVNOSL+CMR8 Type 1C yes yes yes 10 0
FDPQQI+CMMI12 Type 1C yes yes yes 11 0
DGIYWD+DejaVuSerif CID TrueType yes yes yes 13 0
如果您将单个 ID 传递给 $game = Games::find($game);
,它将返回一个 find
模型或 Game
。但是如果你传递一个 id 数组(即使它是一个长度为 1 的数组)或一个模型(出于某种原因),它会返回一个 null
或 Collection
。
在您的修补程序会话中,尝试此操作,您将抛出相同的错误。
null
,
find()
的正常用法是传递一个 id,它会返回该 id 的模型实例。但是,如果您传入一个数组或一个实现 \Illuminate\Contracts\Support\Arrayable
的对象,它将返回所有找到的实例的 Collection
。
你的控制器代码是这样的:
$game = Games::find($game);
如果这里传递给 $game
的 find()
值是一个数组,它将返回一个 Collection
使用数组中的 id 找到的所有模型。
这里的另一个棘手问题是,此处传递到 $game
的 find()
值是否是模型实例。在这种情况下,此语句将返回 Collection
,因为模型实现了上述 Arrayable
契约。
因此,当您调用 find()
并传入模型时,它会在该模型上调用 toArray()
,尝试为数组中返回的每个值查找记录,并返回一个 {{1} } 找到的所有记录。
在任何一种情况下,Collection
现在都是 $game
,当您尝试调用 Collection
时会出现错误,因为 $game->players()
方法不存在关于集合。