Laravel与将可变大小写更改为蛇形大小写 [英] Laravel "with" changes variable case to snake case
问题描述
在我的Laravel应用中,我有一个模型,该模型定义了如下关系:
In my Laravel app, I have A model that defines a relationship like:
public function vitalCategories()
{
return $this->belongsToMany(
'App\Models\Diagonals\VitalLabelCategory',
'vitalLabelCategoryMap',
'vitalLabelId',
'vitalLabelCategoryId');
}
当我查询如下记录时,我希望该关系可以使用变量名称vitalCategories
When I query a record like below, I expect the relation to be available with the variable name vitalCategories
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
return json_encode($vitalLabel);
但是,上面的查询生成的变量名称为'vital_categories'的关系如下:
However, the above query produces the relation with the variable name 'vital_categories' like this:
如何让laravel停止更改变量的大小写以使其与蛇形情况有关?
只是出于笑容,我也尝试过:
Just for grins, I also tried:
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
$vitalLabel->load('vitalCategories');
$vitalLabel->vitalCategories = $vitalLabel->vitalCategories() ;
return json_encode($vitalLabel);
未能查看相关模型:
所以我尝试了:
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
$vitalLabel->load('vitalCategories');
$vitalLabel->vitalCategories = $vitalLabel->vital_categories;
return json_encode($vitalLabel);
也没有看到相关模型:
推荐答案
当模型转换为数组(toArray()
)或json(
Laravel automatically converts the names of relationships from camelCase
to snake_case
when the model is converted to an array (toArray()
) or json (toJson()
).
因此,模型上的属性实际上是vitalCategories
,但是当您将其转储为json时,它将打印为vital_categories
.
So, the attribute on the model is actually vitalCategories
, but when you dump it out as json, it will print as vital_categories
.
如果要关闭此功能,可以将模型的$snakeAttributes
属性设置为false.
If you would like to turn this off, you can set the $snakeAttributes
property on your model to false.
public static $snakeAttributes = false;
这篇关于Laravel与将可变大小写更改为蛇形大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!