Can I use camelCase with Laravel 4 eloquent?

假装没事ソ 提交于 2020-02-03 05:18:06

问题


I have existing data in a mysql db whose columns are camelCased. I can't change them to snake case.

For instance: when I try to use "jobRole", I get "job_role". I want it to be "jobRole".

Is there a setting in laravel to support this? I've read about mutators but don't understand them. Is that the solution? If so, how do I do this?


回答1:


Discovered you can do this.

In the model, redefine "snakeAttributes" to "false" like this:

class YourModel extends Eloquent{
    public static $snakeAttributes = false;
}



回答2:


You can now. I've just completed a package that allows you to work with model attributes completely in camelCase, if required.

https://github.com/kirkbushell/eloquence

Install the package as per normal:

composer require kirkbushell/eloquence ~1.0

Then setup your service providers:

'KirkBushell\Eloquence\EloquenceServiceProvider',

Then all you need to do is either setup Eloquent to point to the new class as part of your aliases in application/config/app.php:

'Eloquent' => 'KirkBushell\Eloquence\Database\Model',

That ensures that the library is basically a drop-in replacement. If you want to just test with some models, you can simply extends the Eloquence base model class:

class MyModel extends \KirkBushell\Eloquence\Database\Model

I built this class mainly because I was sick of seeing snake_case in our javascript applications, but also in our server-side code. This ensured that everywhere (front-end and back-end) was dealing with camel casing.




回答3:


You can't I'm afraid. This bug: https://github.com/laravel/laravel/issues/788 explains more but the long and short of it is that you need the field names to be all lowercase for the models to work.



来源:https://stackoverflow.com/questions/18584091/can-i-use-camelcase-with-laravel-4-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!