How to convert SQL with CAST function in Eloquent
I have a problem with this sql.
SELECT wp_posts.*
FROM wp_posts
JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_date > '2017-04-20 23:59:59'
AND wp_postmeta.meta_key = 'views'
ORDER BY wp_postmeta.meta_value+0 DESC
LIMIT 0, 10
This query returns the most viewed posts. I want to convert it to Eloquent.
+3
source to share
1 answer
Assuming you have configured wp_posts
and wp_postmeta
modal as stated in this tutorial , the below request will do what you need.
$dp = DB::getTablePrefix();
$order_by = "CAST(" . $dp . "postmeta.meta_value AS unsigned) DESC";
BlogPost::with('postmetas')
->where('posts.post_date', '>', '2017-04-20 23:59:59')
->where('postmeta.meta_key', 'views')
->orderByRaw($order_by)
->limit(10)
->get();
Hope this helps!
+1
source to share