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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建