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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog