寫代碼的時候發現一個排序的問題tp5.1 的order 函數 如果排序字段是字符串類型的小數,你會發現使用order函數怎么排序都不正常,看到這個現象你們大概也猜到原因了,到最后執行sql的時候類型沒有轉化,那怎么處理這個呢?
我使用的是sql 直接轉換,那么問題來了,怎么自定義排序,或者說怎么在模型排序中間加上自定義的一段sql排序,可以使用orderRaw函數,看看源碼的介紹
/**
* 表達式方式指定Field排序
* @access public
* @param string $field 排序字段
* @param array $bind 參數綁定
* @return $this
*/
public function orderRaw($field, $bind = [])
{
if ($bind) {
$this->bindParams($field, $bind);
}
$this->options['order'][] = $this->raw($field);
return $this;
}
看這個源碼可以知道,第一個參數你寫什么直接回原封不動的丟到sql中去,第二個參數是參數綁定只有在外部傳值的時候需要(從瀏覽器獲取值傳入sql),所以,忽略$bind參數,讓它為空就好(不管它)
所以最后的排序的的寫法為:
return $this->hasMany('testuModel','product_id','id')->orderRaw("CONVERT(price, DECIMAL) ASC")->order('count', 'asc')->order('id', 'desc')
執行的sql
SELECT * FROM `test` WHERE `product_id` = 3 AND `product_id` = 3 ORDER BY CONVERT(price, DECIMAL) ASC,`count` ASC,`id` DESC