在Laravel中,如何使用数据库表列和骆驼壳的模型属性 [英] In Laravel how to use snake case for database table columns and camel case for model attributes

查看:234
本文介绍了在Laravel中,如何使用数据库表列和骆驼壳的模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的laravel 4,我正在尝试创建一个休息API遵循Apigee定义的最佳做法。



由apigee定义的最佳做法之一是使用骆驼案例进行json属性键,这样在Javascript中使用API​​时,相应的对象将遵循属性代码约定(骆驼香烟盒)。



我想要能够在snake case之后定义datatable列,但是通过我的api检索有说服力的对象时,相应的JSON必须遵循骆驼案例。



我读了一个可以在模型类中设置的静态变量$ snakeAttributes,其文档说指示属性是否在数组上被包围。我试图重写这个变量并将其设置为false(MyResource类),但是当执行下面的代码时,json仍然出现在snake中:



代码:

  $ resource = MyResource :: find($ id); 
return Response :: json($ resource);

JSON:

 code> {
first_name:'Michael',
created_at:2013-10-24 15:30:01,
updated_at:2013-10-24 15:30 :01
}

有人有一个想法如何解决吗? p>

解决方案

创建BaseModel和一种新的方法来帮助您:





  class BaseModel extends \Eloquent {

public function toArrayCamel()
{
$ array = $ this-> toArray();

foreach($ array as $ key => $ value)
{
$ return [camel_case($ key)] = $ value;
}

return $ return;
}

}

您的型号:

  class MyResource extends BaseModel {
}

然后使用它:

  $ resource = MyResource :: find($ id); 
return Response :: json($ resource-> toArrayCamel());


I am new to laravel 4 and I am trying to create a rest API following best practices defined by Apigee.

One of the best practice defined by apigee is to use camel case for json attribute keys, this way when using the API in Javascript the corresponding objects will follow attributes code convention (camel case).

I want to be able to define datatable columns following snake case but when retrieving eloquent objects though my api, the corresponding JSON has to follow camel case.

I read about a static variable $snakeAttributes that could be set in the model class and its documentation says "Indicates whether attributes are snake cased on arrays". I tried to override this variable and set it to false (MyResource class) but when executing the folowing code, the json still comes in snake case:

Code:

   $resource = MyResource::find($id);
   return Response::json($resource);

JSON:

{ 
first_name: 'Michael', 
created_at: "2013-10-24 15:30:01",
updated_at: "2013-10-24 15:30:01"
}

Does someone have an idea on how to solve that?

解决方案

Create BaseModel and a new method to help you with it:

class BaseModel extends \Eloquent {

    public function toArrayCamel()
    {
        $array = $this->toArray();

        foreach($array as $key => $value)
        {
            $return[camel_case($key)] = $value;
        }

        return $return;
    }

}

Your model:

class MyResource extends BaseModel {
}

And then use it:

$resource = MyResource::find($id);
return Response::json( $resource->toArrayCamel() );

这篇关于在Laravel中,如何使用数据库表列和骆驼壳的模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆