Laravel assumes the database table is the plural f

2020-03-12 03:38发布

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? should i change it to "newses" or should i use "new" for the model name?

4条回答
Anthone
2楼-- · 2020-03-12 03:59

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';
}
查看更多
闹够了就滚
3楼-- · 2020-03-12 04:05

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

查看更多
时光不老,我们不散
4楼-- · 2020-03-12 04:05

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.

查看更多
祖国的老花朵
5楼-- · 2020-03-12 04:07

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

查看更多
登录 后发表回答