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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向