使用 Laravel 4.1 对 UNION 查询进行排序

时间:2023-03-03
本文介绍了使用 Laravel 4.1 对 UNION 查询进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我认为 Laravel 4 和 Laravel 4.1 之间的 union 发生了一些变化.我有 2 个模型.

I think there is something changed in the union between Laravel 4 and Laravel 4.1. I have 2 models.

$photos = DB::table('photos')->select('id', 'name', 'created_at');
$videos = DB::table('videos')->select('id', 'name', 'created_at');

我想合并 2 个查询并使用 created_at 字段对 2 个查询进行排序.

I want to union the 2 querys and order the 2 querys with the created_at field.

$photos = $photos->orderBy('created_at', 'desc');
$combined = $photos->union($videos);

使用 Laravel 4 它给了我这个查询:

With Laravel 4 it gives me this query:

select `id`, `name`, `created_at` from `videos`
union
select `id`, `name`, `created_at` from `photos`
order by `created_at` desc

这工作正常,它将两个查询的结果排序在一起.在 Laravel 4.1 中,它给了我这个查询:

This works ok, it sorts the results for both querys together. In Laravel 4.1 it gives me this query:

(select `id`, `name`, `created_at` from `videos`)
union
(select `id`, `name`, `created_at` from `photos` order by `created_at` desc)

这会产生一个视频列表,然后是一个有序的照片列表.我需要有一个列表,其中对组合查询进行了排序.我想让 Laravel 给我这个查询:

This results in a list of videos and after that an ordered list of photos. I need to have a list where the to combined querys are sorted. I want Laravel to give me this query:

(select `id`, `name`, `created_at` from `videos`)
union
(select `id`, `name`, `created_at` from `photos`)
order by `created_at` desc

如何在 Laravel 中实现此功能?

How do get this working in Laravel?

推荐答案

似乎在这个 pull request 中修复了:https://github.com/laravel/framework/pull/3901

It seems to be fixed in this pull request: https://github.com/laravel/framework/pull/3901

这篇关于使用 Laravel 4.1 对 UNION 查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何正确捕获 PHP 异常 (Laravel 5.1) 下一篇:Laravel 模型函数“create"和“create"有什么区别?和“插入"?

相关文章