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

哪个是在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.

我一直在使用Laravel大约2个月。 我只是想知道如何以正确的方式定义模型。 p>

例如,我以这种方式定义模型的方法。 p>

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

在模型中,我定义了静态和非静态方法。 p>

我想知道哪一个是更好的使用方式,因为Laravel似乎使用了很多静态方法。 p> div>

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