我在訂購/排序結果時遇到問題。 基本上我有職位表和我計數popular_count根據多少評論和喜歡它有。事情是,我也分頁結果。所以 當我使用這樣的Laravel - PopularityCount屬性 - 訂購者
$Posts->paginate(5);
$Posts->sortBy('popularity_count');
$Posts->get();
它排序只對特定的頁面,所以如。第1頁有流行結果計數如:6,5,4,3,2,第二頁有10,7,5,2,1。正如你所看到的那樣,有一些熱門文章,它應該是第一頁的第一個結果。
當我嘗試使用
$Posts->orderBy('popularity_count')
這是行不通的,因爲我不我的數據庫這樣有列。有沒有可能實現我想要的,而不使用RAW選擇和連接?我的模型上有更多的自定義屬性。
謝謝!
編輯:
`public function getPopularityCountAttribute(){
$comments = $this->getRelation('commentsCount');
$likes = $this->getRelation('likesCount');
$comments = ($comments) ? (int) $comments->comments_count : 0;
$likes = ($likes) ? (int) $likes->likes_count : 0;
$Result = $likes + ($comments * 1.2);
return $Result;
}`
嘗試使用DB ::原始的sql查詢...我不知道如何編寫查詢。 – Sherif