【问题标题】:Define custom attributes in Eloquent在 Eloquent 中定义自定义属性
【发布时间】:2017-02-15 08:57:53
【问题描述】:

我在数据库中有 3 个不同的字段:citystatecountry。如何在 Eloquent 中定义另一个属性以从这 3 个字段中返回一个字符串?

第一种方法,但它不起作用:

protected $address = "";

public function getAddress() : string {
  return $this->city . $this->state . " - " . $this->country;
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    如果您想要一个未在模型中定义的新属性,则需要将该属性附加到您的模型中。

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['address'];
    

    并定义你的属性方法:

    /**
     * Get the address.
     *
     * @return string
     */
    public function getAddressAttribute()
    {
        return $this->city . $this->state . " - " . $this->country;
    }
    

    【讨论】:

      【解决方案2】:

      在方法名称中添加Attribute 使其工作:

      public function getAddressAttribute()
      {
          return $this->city.$this->state.' - '.$this->country;
      }
      

      https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

      【讨论】:

      • 不过,这适用于已经映射到数据库表的属性。当我调用$this->address 时它什么也不返回
      猜你喜欢
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      相关资源
      最近更新 更多