Eloquent 首先使用自定义的偏好顺序
Eloquent first with a custom defined preference order
是否有一种更简短、更优雅的方法来指示 eloquent 中的第一个方法使用自定义首选项顺序选取匹配记录?
示例:(选择配置 A,然后选择 B,然后选择默认值)
$config = Configs::whereIn('section', ['A','B', 'default'])
->first() // Picks A or B or default;
无需编写如下代码
$config = Configs::where('section', 'A');
if(!$config)
config = Configs::where('section', 'B');
elseif(!$config)
config = Configs::where('section', 'default');
您可以简单地提供一些基于 section
的排序,->first()
将 select “正确”的记录:
$config = Configs::whereIn('section', ['A', 'B', 'default'])
->orderBy('section')
->first();
如果 section: A
存在,则 $config
将是 A
,将根据顺序隐式回退到 section: B
或 section: default
。
编辑:Config:: -> Configs::
,但请记住,Laravel 模型名称按照惯例是单数的。
是否有一种更简短、更优雅的方法来指示 eloquent 中的第一个方法使用自定义首选项顺序选取匹配记录?
示例:(选择配置 A,然后选择 B,然后选择默认值)
$config = Configs::whereIn('section', ['A','B', 'default'])
->first() // Picks A or B or default;
无需编写如下代码
$config = Configs::where('section', 'A');
if(!$config)
config = Configs::where('section', 'B');
elseif(!$config)
config = Configs::where('section', 'default');
您可以简单地提供一些基于 section
的排序,->first()
将 select “正确”的记录:
$config = Configs::whereIn('section', ['A', 'B', 'default'])
->orderBy('section')
->first();
如果 section: A
存在,则 $config
将是 A
,将根据顺序隐式回退到 section: B
或 section: default
。
编辑:Config:: -> Configs::
,但请记住,Laravel 模型名称按照惯例是单数的。