呃......很抱歉,检测到您当前浏览器兼容性较差,为了保证您有更高品质的使用体验

1.若当前为360浏览器,请切换至 极速模式

2.若当前为IE浏览器,建议更换为 谷歌浏览器

laravel Model 表名自动复数加s或ies等源码分析

在开发laravel Model时如果不指定table 框架会自动把表名进行复数形式作为你的表名,看看laravel源码是怎么做到的吧。

//文件:Illuminate\Database\Eloquent\Model;

/**
* Get the table associated with the model.
* 在这里获取表名,使用了 Str::pluralStudly()
* @return string
*/
public function getTable()
{
    return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
}

//就在str工具这里:Illuminate\Support\Str;

/**
* Get the plural form of an English word.
* 获取英语单词的复数形式
* @param  string  $value
* @param  int  $count
* @return string
*/
public static function plural($value, $count = 2)
{
    return Pluralizer::plural($value, $count);//又调用了:Illuminate\Support\Pluralizer;
}

在Pluralizer::plural里最终调用了另一个第三方库:https://github.com/doctrine/inflector
Doctrine Inchector是一个小型库,可以对单词的大写/小写和单数/复数形式执行字符串操作。

以上就是laravel Model 表名自动复数加s或ies等源码分析

如果不想使用这种命名方式,可以自定义表名:


class testTable extends Model
{
    use HasFactory;
    protected $table = 'test_table'; // 在这指定一个表名


}

转载需保留出处:https://2weima.com/article/read.html?scene=R6666L-o6666L-45E3F6
且未经用户允许禁止转载