如果我有一个模型“狗”,Laravel会将它链接到“Dogs”表。永远是复数。 现在,如果我有一个模型“人物”,它会尝试找到表“人物” - 也就是复数。但是,当Laravel不仅仅是添加“s”时,他们如何知道复数? 是否有一个包含所有英语名词的表格?
答案 0 :(得分:34)
在Illuminate\Database\Eloquent\Model.php
中,您会发现类似str_plural($name)
和str_plural
的内容是使用Str::plural
方法的辅助函数,在这种情况下,此方法如下所示:
public static function plural($value, $count = 2)
{
return Pluralizer::plural($value, $count);
}
所以很明显,Str::plural
使用了类Illuminate\Support\Pluralizer.php
,在那里你会发现它实际上是如何工作的。只需阅读源代码。 irregular word forms
与其他人有单独的字映射:
// Taken from Illuminate\Support\Pluralizer
public static $irregular = array(
'child' => 'children',
'foot' => 'feet',
'freshman' => 'freshmen',
'goose' => 'geese',
'human' => 'humans',
'man' => 'men',
'move' => 'moves',
'person' => 'people',
'sex' => 'sexes',
'tooth' => 'teeth',
);
答案 1 :(得分:20)
Alpha的答案是Laravel 4。
为了给予应有的信用,我想更新Laravel 5的答案。
Pluralizer
现在从doctrine/inflector延伸,以避免重新发明轮子。该库包含一些基本规则,例如
(m|l)ouse => _ice
(buffal|tomat)o => _oes
...all else... => append 's'
其次是一些“未反射”(即单数和复数相同)
deer, fish, etc.
最后是不规则的规则,例如
man => men
ox => oxen
来自文档:
Doctrine inflector有静态方法来调整文本。
这些类中的方法来自收集的几个不同来源 跨几个不同的PHP项目和几个不同的作者。该 原作者姓名和电子邮件不详。
Pluralize& Singularize实现是从CakePHP借来的,并进行了一些修改。
所以有趣的是,所有框架都互相借用和重用。
答案 2 :(得分:0)
嘿,没有人告诉过我们也可以使用这个函数 LIKE :
$peopleSingular = Pluralizer::singular('people');
$peoplePlural = Pluralizer::plural('person');
谢谢