0

我遇到了我认为很简单的事情,我只是想多了。我在 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,
           user_id: 1,
         },
       },
     ],
   }

我基本上已经在我的控制器中放置了完全相同的代码来拉取游戏中的玩家列表:

    $game = Games::find($game);
    $players = $game->players()->get();

当我到达路线时,我得到了这个:

Method Illuminate\Database\Eloquent\Collection::players does not exist.

我很困惑,如果它在 Tinker 中工作得很好,为什么它不能在控制器中工作。

谢谢您的帮助!

4

2 回答 2

1
$game = Games::find($game);

如果您将单个 id 传递给find,它将返回一个Game模型或null. 但是,如果您传递一个 id 数组(即使它是一个长度为 1 的数组)或一个模型(出于某种原因),它将返回一个Collectionor null

在你的修补会话中,试试这个,你会抛出同样的错误。

$game = Games::find(1);
$game = Games::find($game);
// or
$game = Games::find([1]);

$players = $game->players()->get();
于 2020-12-18T23:02:55.000 回答
1

的正常用法find()是传递一个 id,它将返回该 id 的模型实例。但是,如果您传入一个数组或一个实现 的对象\Illuminate\Contracts\Support\Arrayable,它将返回Collection所有找到的实例中的一个。

您的控制器代码是这样的:

$game = Games::find($game);

如果$game传入find()这里的值是一个数组,它将返回Collection使用数组中的 id 找到的所有模型中的一个。

这里的另一个偷偷摸摸的问题是$game传递到find()这里的值是否是模型实例。在这种情况下,该语句将返回 a Collection,因为模型实现了上述Arrayable契约。

因此,当您调用find()并传入模型时,它将调用toArray()该模型,尝试为数组中返回的每个值查找记录,并返回Collection找到的所有记录。

无论哪种情况,$game现在都是 a Collection,当您尝试调用 时,您会收到错误消息$game->players(),因为该players()方法在集合中不存在。

于 2020-12-18T23:03:02.960 回答