在我的Laravel应用程序中,我有一个模型,它定义了如下关系:
![enter image description here](https://istack.dev59.com/NyAJE.webp)
如何让 Laravel 停止将我的变量命名为蛇形命名法(snake case)?
只是为了好玩,我也尝试了:
public function vitalCategories()
{
return $this->belongsToMany(
'App\Models\Diagonals\VitalLabelCategory',
'vitalLabelCategoryMap',
'vitalLabelId',
'vitalLabelCategoryId');
}
当我像下面这样查询记录时,我期望使用变量名 vitalCategories
可以访问关系。$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
return json_encode($vitalLabel);
然而,上面的查询生成了一个名为“vital_categories”的变量,如下所示:![enter image description here](https://istack.dev59.com/NyAJE.webp)
如何让 Laravel 停止将我的变量命名为蛇形命名法(snake case)?
只是为了好玩,我也尝试了:
$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);
该模型也未能看到相关的模型:
static $snakeAttributes = false;
(静态 vs 受保护),但你做得很好,谢谢! - Wesley Smithpublic
公开的。抱歉,我更多地是根据记忆而不是查看实际代码。我已经更新了答案。谢谢! - patricusload()
方法而不是在toArray()
方法中不需要此属性。 - toraman