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

tom*_*ato 0 php laravel eloquent laravel-5

我有一个名为的模型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::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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果可能,我希望能够按此自定义属性进行订购

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

有没有办法用 Laravel 查询构建器来做到这一点?

Jer*_*dev 5

如果不将此函数转换为 SQL 语句,您将无法在查询中使用此属性。

但是,您可以查询此模型,然后使用该sortBy函数对其进行排序。这将在从数据库中获取后在内存中对您的集合进行排序。

$customers = Customers::get()->sortBy('name');
Run Code Online (Sandbox Code Playgroud)

请记住,对于大型集合(> ~10k),不建议这样做。然后您应该考虑将其转换为 SQL 语句。