如何将带有CAST函数的SQL转换为Eloquent

时间:2017-05-31 10:33:15

标签: php mysql wordpress laravel eloquent

我的这个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

此查询返回查看次数最多的帖子。我想把它转换为Eloquent。

1 个答案:

答案 0 :(得分:1)

假设您已按this tutorial中所述设置了wp_postswp_postmeta模式,那么以下查询将为您完成此任务。

$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();

希望这有帮助!