如何在单个路由定义中隐式绑定多个 Eloquent 模型?

How to implicitly binding multiple Eloquent models in a single route definition?

Laravel9 文档说:

When implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the previous Eloquent model. For example, consider this route definition that retrieves a blog post by slug for a specific user:

   use App\Models\Post;
   use App\Models\User;
 
    Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
    });

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the User model has a relationship named posts (the plural form of the route parameter name) which can be used to retrieve the Post model. Blockquote

但它 returns 错误:BadMethodCallException 调用未定义的方法 App\Models\User::posts()

让我强调这句话 第二个 Eloquent 模型,它必须是前一个 Eloquent 模型的子模型

根据突出显示的句子,您必须在 User 模型中定义一个 posts 关系函数,因为 Laravel 假设第二个片段是第一个片段的子片段,这意味着第一段必须与第二段有 hasMany 关系,如下所示,

public function posts()
{
   return $this->hasMany(Post::class);
}