简体   繁体   English

Laravel,相关模型重新命名

[英]Laravel, related model reuturened names

I have a model that has a related model 我有一个具有相关模型的模型

class A extends Model{

public function niceName()
    {
        return this->hasOne('App\NiceName2' ...);
    }

In the controller when I retrieve data with submodel the result is like 在控制器中,当我使用子模型检索数据时,结果类似于

a[nice_name_2] (using the table name) and I would like it to be a[NiceName2]. a [nice_name_2](使用表名),我希望它是a [NiceName2]。

Is there a way to have an alias for the returned result? 有没有办法为返回的结果添加别名? In cakePHP i know there is propertyName to set this on relations. 在cakePHP中,我知道有propertyName可以在关系上进行设置。 Laravel has a similar feature? Laravel有类似的功能吗?

Thanks 谢谢

Laravel uses the convention of camelCase for method names and snake_case for attributes. Laravel使用camelCase的约定作为方法名,使用snake_case的约定作为属性。 I'm not sure there's an easy way around this. 我不确定这是否有简单的方法。

When Laravel serializes the data, it converts relationships to snake_case, by convention. 当Laravel序列化数据时,按照约定它将关系转换为snake_case。 So NiceName2 would become nice_name2 when you execute toArray() or when the model is serialized (either in a JSON response or otherwise). 因此,当您执行toArray()或对模型进行序列化时(在JSON响应中或其他方式), NiceName2将变为nice_name2

How this works is: 这是如何工作的:

When you access $model->nice_name2 it converts the property name back to niceName2 to check for a relationship method with that name. 当您访问$model->nice_name2它将属性名称转换回niceName2以检查具有该名称的关系方法。 When serializing, it converts the relationship niceName2 to the attribute name nice_name2 . 序列化时,它会将关系niceName2转换为属性名称nice_name2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM