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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程