dougu3290 2015-04-17 15:52
浏览 85
已采纳

Laravel方法模型绑定?

I'm moving a large project from CodeIgniter to Laravel 5, and am encountering a problem that I can't seem to find a solution for.

I know you can do route model binding, and I've been using it extensively without problem, and I know you can do method injection, such as injecting the Request into the method.

But my "problem" is I have multiple classes with the same name, but for different sections of the project, for example:

App\Models\Knowledgebase\Article
App\Models\News\Article
App\Models\Minisite\Resources\Article

As you can see, I have 3 different Article models. One for Knowledgebase Articles, one for news articles and one for departmental resource articles.

However, with route model binding, it seems I can only bind one model to a keyword, and since my URLs each have the keyword Article, it doesn't really work.

So my question is, is it possible to inject the related model into the method by specifying it as a parameter? Or do I need to hard code it into the method by saying:

$article = App\Models\Knowledgebase\Article::find($some_id);

Or can I do something like this:

public function show(App\Models\Knowledgebase\Article $article)
{
   // code
}

At the moment, if I try to inject the article, $article becomes a new instance of the Article model, rather than the model record. It just seems a bit weird that the framework would make you manually retrieve the model for each method.

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • dongzipu7517 2015-04-17 16:02
    关注

    However, with route model binding, it seems I can only bind one model to a keyword, and since my URLs each have the keyword Article, it doesn't really work.

    You can use a different keyword in the bindings for each type.

    // in the router
    $router->model('kbarticle', 'App\Models\Knowledgebase\Article');
    $router->model('newsarticle', 'App\Models\News\Article');
    $router->model('sitearticle', 'App\Models\Minisite\Resources\Article');
    
    // in your routes file
    Route::get('knowledge/{kbarticle}', function(App\Models\Knowledgebase\Article $article) {});
    Route::get('news/{newsarticle}', function(App\Models\News\Article $article) {});
    Route::get('site/{sitearticle}', function(App\Models\Minisite\Resources\Article $article) {});
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?