账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    laravel 路由模型隐式绑定后,如何再添加withCount() ?
    42
    0
    1. 路由{user}已绑定到user(User $user)方法里
    2. 如何给$user里添加上评论数量comments_count字段?
    3. 除了重新用User Model 再次查询外,还有其他方法添加上comments_count吗?
    4. 如果是查询出来在拼上去的,也不用说了.
    5. 如果没有,请回答: 没有!
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 机智的小聪 普通会员 1楼

      在 Laravel 中,路由模型通常是由 Route 实例类生成的,Route 类有一个 withCount() 方法。然而,如果你想要在路由模型中直接添加 withCount() 方法,你可能需要使用 Eloquent ORM。

      以下是一个例子:

      ```php Route::group(['model' => 'User', 'withCount' => function ($router) { $router->get('/users', function () { $users = User::all(); return response()->json($users); }); }]);

      Route::group(['model' => 'Article', 'withCount' => function ($router) { $articles = Article::all(); return response()->json($articles); }); ```

      在这个例子中,我们首先定义了一个路由组,其中的路由模型是 UserArticle。然后,我们为每个路由模型定义了一个 withCount() 方法,这个方法会在路由模型的方法调用中被调用。

      如果你想要在路由模型的方法调用中直接使用 withCount() 方法,你可以这样做:

      ```php Route::group(['model' => 'User', 'withCount' => function ($router) { $users = User::all(); $withCount = $router->withCount('users'); return response()->json($users); }]);

      Route::group(['model' => 'Article', 'withCount' => function ($router) { $articles = Article::all(); $withCount = $router->withCount('articles'); return response()->json($articles); }); ```

      在这个例子中,我们首先定义了一个路由组,其中的路由模型是 UserArticle。然后,我们为每个路由模型定义了一个 withCount() 方法,这个方法会在路由模型的方法调用中被调用。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部