duanaidang6197 2017-06-28 04:43
浏览 44
已采纳

Laravel“with”将可变案例更改为蛇案

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');
}

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);

However, the above query produces the relation with the variable name 'vital_categories' like this:

enter image description here

How can I make laravel stop changing the case of my variable for the relation to snake case?

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);

which failed to see the related models:

enter image description here

so then I tried:

$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
$vitalLabel->load('vitalCategories');
$vitalLabel->vitalCategories = $vitalLabel->vital_categories;
return json_encode($vitalLabel);

which also failed to see the related models:

enter image description here

  • 写回答

1条回答 默认 最新

  • duan36000 2017-06-28 05:09
    关注

    Laravel automatically converts the names of relationships from camelCase to snake_case when the model is converted to an array (toArray()) or json (toJson()).

    So, the attribute on the model is actually vitalCategories, but when you dump it out as json, it will print as vital_categories.

    If you would like to turn this off, you can set the $snakeAttributes property on your model to false.

    public static $snakeAttributes = false;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件