Laravel假定数据库表是模型名称的复数形式

问题描述 投票:9回答:4

默认情况下,Laravel假定数据库表是模型名称的复数形式。但是,如果我的表名是“新闻”,而我仍想使用此功能怎么办?我应该将其更改为“新闻”还是应该使用“新”作为模型名称?

laravel eloquent
4个回答
10
投票

如果您的模型以字母's'结尾,它将保持表名相同。对于您而言,您的模型默认将表命名为news

但是如果您想使用其他名称,则可以使用:

protected $table = 'tablename';

在模型内部。

编辑:我在应用程序中对此进行了测试。我制作了一个名为News的模型。然后,我创建了一个新的News实例并检索了表名:

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

它返回:news


8
投票

您可以通过如下在模型上定义表属性来指定自定义表

<?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


6
投票

在雄辩的模型中,您必须定义table name。例如,如果我的模型名为user,数据库中的表名为user_of_application,那么我这样做[]

class user extends Model
{
    protected $table = 'user_of_application';
}

1
投票

Laravel使用定义以下内容的“标准集”规则:

© www.soinside.com 2019 - 2024. All rights reserved.