Laravel 5.2更改数据库列名引用

3
你好,我正在尝试更改访问数据库列名的方法,而不更改名称。例如,我的列名是resourceType,但我想将其称为name。同时,我希望响应JSON显示name而不是resourceType。在互联网上搜索时,我发现应该使用protected $maps = ['oldName' => 'newName'];,但这并没有起作用。我想更改resourceType,因为我认为表格名称和列名不应该相等:resourceType->resourceType
这是我的模型:
<?php

namespace Knotion;

use Illuminate\Database\Eloquent\Model;
use Mappable, Mutable;

class CTL_ResourceType extends Model  {
  public $timestamps = false;
  protected $table = "CTL_ResourceType";
  protected $primaryKey = "idResourceType";

  public $incrementing = false;
  public static $snakeAttributes = false;

  protected $hidden = ['idCountry', 'idCompany', 'initials', 'thumbnail', 'icon', 'status', 'createTime', 'updateTime'];
  protected $fillable = ['name'];

protected $maps = ['resourceType' => 'name'];
protected $appends = ['name'];

  public function resource()  {
    return $this->hasMany('Knotion\CTL_Resource', 'idResource' );
  }
  public function country() {
    return $this->belongsTo('Knotion\CTL_Country', 'idCountry', 'idCountry');
  }
  public function company() {
    return $this->belongsTo('Knotion\CTL_Company', 'idCompany', 'idCompany');
  }


}

这是我收到的响应JSON。你可以看到,resourceType仍然存在,而不是name

{
  "total": 16,
  "per_page": 15,
  "current_page": 1,
  "last_page": 2,
  "next_page_url": "http://localhost:8000/krb/api/resources?page=2",
  "prev_page_url": null,
  "from": 1,
  "to": 15,
  "data": [
    {
      "idResource": "4e8f1ece-f666-11e5-8137-0f7932903a75",
      "productionKey": "238493ujjsl",
      "title": "ElTitle16",
      "description": "ElDescription16",
      "minimumAge": "4",
      "maximumAge": "15",
      "fileName": "ElFileName16",
      "extension": ".png",
      "URL": "ElURL16",
      "createTime": "2016-03-30 04:58:16",
      "creatorUser": {
        "idUser": "85cf125c-f5ff-11e5-8137-0f7932903a75",
        "name": "Roberto"
      },
      "creationCountry": {
        "idCountry": "f03a75a0-f5ff-11e5-8137-0f7932903a75",
        "country": "Estados Unidos"
      },
      "resourceType": {
        "idResourceType": "5c902028-f601-11e5-8137-0f7932903a75",
        "resourceType": "TípodeRecurso3"
      },
      "tags": [
        {
          "idTag": "40c6a114-f520-11e5-8137-0f7932903a75",
          "name": "ElTag1"
        }
      ],
      "quickTags": [
        {
          "idQuickTag": "679bc8f0-f520-11e5-8137-0f7932903a75",
          "name": "ElQuickTag4"
        }
      ],
      "relatedTo": [
        {
          "idRelatedTo": "7beddc6c-f520-11e5-8137-0f7932903a75",
          "name": "ElRelatedTo3"
        }
      ]
    }

你为什么不直接在Artisan中执行migrate:refresh命令迁移数据库呢? - Juakali92
他们已经给了我一个设计好的数据库,只有SQL。 - CanKer
啊,我明白了,那有点糟糕。 - Juakali92
是的,我有一些Laravel的经验,但只是在使用迁移时。因为这个项目一直困扰着我,但多亏了互联网和分享知识的人,我正在学到很多东西。 :) - CanKer
是的,我从来没有使用Artisan时没有修改数据库的自由。但我也见过一些数据丢失的情况,所以我可以理解为什么会使用这些变通方法。 - Juakali92
1个回答

1

我之前没听说过$maps属性或Mappable,所以我进行了快速搜索。看起来它们(以及Mutable)都是jarektkaczyk/eloquence包的一部分。

在这种情况下,MappableMutable都是应该添加到类中的traits。此外,为了让它们正常工作,您需要添加Eloquence trait。

您文件顶部的use语句需要更改以正确地定位正确名称空间中的类名,然后您需要将trait添加到您的类:

<?php
namespace Knotion;

// import the class names
use Sofa\Eloquence\Mutable;
use Sofa\Eloquence\Mappable;
use Sofa\Eloquence\Eloquence;
use Illuminate\Database\Eloquent\Model;

class CTL_ResourceType extends Model  {

    // add the traits to the class
    use Eloquence, Mappable, Mutable;

    // code...
}

编辑

如果您想在不使用该软件包的情况下完成此操作,您需要执行三个步骤:

  1. You need to add resourceType to your $hidden array, so that it won't show up in your toArray()/toJson() results.

    protected $hidden = ['idCountry', 'idCompany', 'initials', 'thumbnail', 'icon', 'status', 'createTime', 'updateTime', 'resourceType'];
    
  2. You need to create a getNameAttribute() accessor method, which will be called whenever you attempt to access the name attribute.

    public function getNameAttribute() {
        return $this->resourceType;
    }
    
  3. You need to add name to your $appends array, so that it will be included in your toArray()/toJson() results.

    protected $appends = ['name'];
    

如果觉得这样做太麻烦,你也可以选择覆盖toArray()方法(由toJson()调用),来强制使用你的命名约定:

public function toArray() {
    // call parent method to get initial array results
    $array = parent::toArray();

    // set the new key with data
    $array['name'] = $array['resourceType'];

    // unset the old key
    unset($array['resourceType']);

    // return the array
    return $array;
}

非常感谢您,先生。今天早上我听说过那个解决方案,但我想看看是否有其他不需要包的解决方案,但似乎没有。再次感谢您的帮助。您应该得到一个在天堂的位置,就在查尔斯·巴贝奇或者您想要的任何人旁边。:P 谢谢您,我非常感激您的帮助和时间。 - CanKer
@CanKerDiAlike 没问题。我不知道你想要避免使用这个包,所以我在我的答案中更新了一些选项,并附上了解释。希望能对你有所帮助。 - patricus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接