doukun8944 2014-01-07 13:21
浏览 74
已采纳

哪个是在Laravel中定义Model的方法的更好方法?

I have been using Laravel for about 2 months. And I'm just wondered about how to define models in the proper way.

For example, I define model's method in this way.

public static get_book_static($id){
   return Book::where($id)->first();
}

public get_book($id){
   return Book::where($id)->first();
}

In models, I defined the methods both in static and not.

I want to know that which one is the better way to use, because Laravel seems to use a lot of static methods out there.

  • 写回答

1条回答 默认 最新

  • drhe80011 2014-01-07 16:34
    关注

    There isn't a better way. Static is necessary in some cases and in some cases it is not. If you need to call a method statically with instantiating a model object first, then it needs to be static. For example, in your controller:

    $myBook = Book::find($id); // find() is built into Laravel's ORM
    
    $myBook->doSomething(); // doSomething() is a custom non-static function that you added to your Book model.
    
    $anotherBook = Book::findSomeOtherType(); // findSomeOtherType() is a custom static function you added to the Book model.
    

    Also, it looks like you are doing extra, unnecessary work. The Book object IS your model:

    Book::where($id)->first();
    

    is the same as

    Book::find($id);
    

    You shouldn't have to create any sort of public get_book($id) function. Just use Book::find($id) directly in your controller.

    http://laravel.com/docs/eloquent

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加