Laravel assumes the database table is the plural form of the model name

前端 未结 4 1469
南笙
南笙 2021-01-11 14:09

By default, Laravel is assuming that the database table is the plural form of the model name. But what if my table name is \"news\" and i still want to use this feature? sho

相关标签:
4条回答
  • 2021-01-11 14:43

    Laravel uses a "standard set" rule that defines:

    • A Model is a single instance of a record
    • A Collection is one or more records

    Therefore it assumes that a table is a collection of records.

    The nomenclature has a problem when it clashes with various features / gotchas of human languages. For example, what if I have a Model called Sheep? That does mean my Database Table should be called "Sheeps"?

    It's up to the developer to avoid "Gollum/Smeagol" syntax. Indeed, you wouldn't want a table called "Newses" as much I'd like to end up with a table called "Sheeps".

    Ultimately, I construct Migrations with:

    sudo php artisan make:migration create_sheep_table --create=sheep
    

    As for Models, you'll notice in the documentation that they have a different table name for "Flights" called "my_flights"

    https://laravel.com/docs/master/eloquent#defining-models

    Again, it's up to the developer / DB manager to make decisions on naming conventions that make sense in an application context.

    0 讨论(0)
  • 2021-01-11 14:51

    You may specify a custom table by defining a table property on your model as below

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Flight extends Model
    {
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_flights';
    }
    

    Ref:https://laravel.com/docs/5.1/eloquent

    0 讨论(0)
  • 2021-01-11 14:53

    Inside your eloquent model you have to define table name. For example if my model is named user and table in database is named user_of_application then i do it this way

    class user extends Model
    {
        protected $table = 'user_of_application';
    }
    
    0 讨论(0)
  • 2021-01-11 14:57

    If you have a model ending with the letter 's', it will keep the table name the same. In your case, your model will name your table news by default.

    If you want to use another name though, you can use:

    protected $table = 'tablename';
    

    inside of your model.

    EDIT: I tested this in my application. I made a model named News. Then I made a new instance of News and retrieved the table name:

    $news = new News();
    dd($news->getTable());
    

    It returns: news

    0 讨论(0)
提交回复
热议问题