使用 Laravel 在模型中映射字段名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29979479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping field name in model using laravel
提问by Casey
Is there a way to map field names to a database to a different attribute name in the model? For example, if the database has a field name of customer_id
but I wanted to use eloquent in this way Customer::get(['id'])
I've tried using the getAttribute method but that is called after eloquent has attempted to get the value.
有没有办法将字段名称映射到数据库到模型中的不同属性名称?例如,如果数据库有一个字段名称,customer_id
但我想以这种方式使用 eloquent,Customer::get(['id'])
我尝试使用 getAttribute 方法,但在 eloquent 尝试获取值后调用该方法。
回答by Jarek Tkaczyk
You can use accessors to work with such attributes, but there's no way to query them this way with core eloquent.
您可以使用访问器来处理这些属性,但无法使用 core eloquent 以这种方式查询它们。
But fear not! Use this package https://github.com/jarektkaczyk/eloquenceand you can easily achieve what you want (Mappable
in particular):
但不要害怕!使用这个包https://github.com/jarektkaczyk/eloquence,你可以轻松实现你想要的(Mappable
特别是):
// Customer model
protected $maps =[
'id' => 'customer_id',
'name' => 'customer_name',
...
];
// then you can do this:
$customer = Customer::where('name', 'whatever')->first();
// calls WHERE customer_name = ? sql
$customer->id; // customer_id column
$customer->name; // customer_name column
$customer->name = 'different name'; // set mutator works as well
It's in heavy development and currently select
is not yet supported, but it's matter of day or two.select
support has been pushed already.
它正在大力开发中,目前select
尚不受支持,但这只是一两天的事情。select
已经推出了支持。