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

在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?

  • 写回答

1条回答 默认 最新

  • dongrong9053 2017-08-09 09:12
    关注

    You will not be able to use this attribute in a query without converting this function into a SQL statement.

    You can however query this model and sort it afterward using the sortBy function. This will order your collection in memory after it has been fetched from the database.

    $customers = Customers::get()->sortBy('name');
    

    Keep in mind that this is not recommended for large collections (> ~10k). Then you should look into converting this to an SQL statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?