【问题标题】:Is there a way to rename Model columns in Lumen?有没有办法重命名流明中的模型列?
【发布时间】:2018-09-29 05:34:17
【问题描述】:

我有一个西班牙语数据库,例如:

create table usuarios
(
    idUsuario int(6) unsigned zerofill not null auto_increment
        primary key,
    estado enum('A', 'B') default 'A' not null,
    nombre varchar(60) not null,
    correo varchar(60) not null,
    clave varchar(32) not null,
    fecha_alta datetime not null,
    fecha_baja datetime null
)
comment 'Usuarios que consumen la API'
;

create index estado
    on usuarios (estado)
;

我在 Lumen 中有以下模型:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable;

  protected $connection = 'api';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

  protected $table = 'usuarios';

  public $timestamps = false;

  protected $fillable = [
        'nombre', 'correo',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
//    protected $hidden = [
//        'clave',
//    ];
}

那么问题是什么?这行得通......但我需要所有英文API,包括参数......但在这种情况下,Lumen 只了解创建和更新方法何时接收西班牙语参数。有没有办法像我对$table = 'usuarios' 那样映射$filleable = ['nombre', 'correo']?我希望像$filleable = ['nombre' =&gt; 'name', 'correo' =&gt; 'email'] 这样的东西可以解决问题,但我在文档中没有看到任何内容。

提前致谢!

【问题讨论】:

  • Eloquent 资源非常适合这个,但我认为它们不是 Lumen 的一部分。您可以制作具有英文名称的访问器并从西班牙语命名列返回内容。

标签: php laravel api eloquent lumen


【解决方案1】:

可能。使用Accessors & Mutators

例如,要从数据库中获取 name 属性,请定义访问器:

public function getNameAttribute() {
    return $this->nombre;
}

要更新name属性到数据库,定义一个mutator:

public function setNameAttribute($value) {
    $this->attributes['nombre'] = $value;
}

定义访问器和修改器后,访问和更新name属性如下:

$name = $user->name; // access the field nombre
$user->name = 'foo';
$user->save(); // update nombre field

【讨论】:

  • 感谢@ben 成功了。此外,我必须重新定义模型的 toArray() 方法,以使其也以英语显示 json 响应
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 2011-03-26
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2011-07-17
相关资源
最近更新 更多