du1462
2017-08-09 09:09
浏览 457
已采纳

在Laravel 5模型中按自定义属性排序?

I have a model called customers which has a custom attribute called name; this can either by a customers full name or the company name depending on what their account type is.

class Customer extends Model
{

    const BUSINESS = "Business";
    const INDIVIDUAL = "Individual";

    protected $table = 'users';
    protected $appends = ['name'];
    private $name;

    public static function boot()
    {
        parent::boot();

        static::created(function () {
        });

        static::updating(function () {
        });
    }


    /**
     * Get the display name for the customer
     * 
     * if Customer::BUSINESS then use company field
     * else if Customer::INDIVIDUAL then use their name
     * 
     * @return mixed|string
     */
    function getDisplayName() {
        return ($this->account == Customer::BUSINESS) ? $this->company : $this->getContactName();
    }

    public function getContactName()
    {
        return ucfirst($this->first_name) . " " . ucfirst($this->last_name);
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->getDisplayName();
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }
}

I want to be able to ORDER BY this custom attribute if possible.

At the moment Laravel throws an error saying name is not a defined column.

Is there a way to do this with Laravel Query builder?

图片转代码服务由CSDN问答提供 功能建议

我有一个名为 customers 的模型,它有一个名为 name <的自定义属性 /代码>; 这可以是客户的全名或公司名称,具体取决于他们的帐户类型。

  class Customer extends Model 
 {
 
 const BUSINESS =“Business  “; 
 const INDIVIDUAL =”Individual“; 
 
 protected $ table ='users'; 
 protected $ appends = ['name']; 
 private $ name; 
 
 public static function boot(  )
 {
 parent :: boot(); 
 
 static :: created(function(){
}); 
 
 static :: updates(function(){
}); \  n} 
 
 
 / ** 
 *获取客户的显示名称
 * 
 *如果Customer :: BUSINESS然后使用公司字段
 * else如果Customer :: INDIVIDUAL则使用其名称\  n * 
 * @return mixed | string 
 * / 
函数getDisplayName(){
 return($ this-&gt; account == Customer :: BUSINESS)?  $ this-&gt; company:$ this-&gt; getContactName(); 
} 
 
公共函数getContactName()
 {
返回ucfirst($ this-&gt; first_name)。  “”。  ucfirst($ this-&gt; last_name); 
} 
 
 / ** 
 * @return mixed 
 * / 
公共函数getName()
 {
返回$ this-&gt; getDisplayName(  ); 
} 
 
 / ** 
 * @param mixed $ name 
 * / 
 public function setName($ name)
 {
 $ this-&gt; name = $ name; 
  } 
} 
   
 
 

我希望能够 ORDER BY 此自定义属性。

目前,Laravel抛出错误,指出 name 不是已定义的列。

有没有办法在Laravel Query构建器中执行此操作?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题