Laravel Eloquent Union 查询

2021-12-18 00:00:00 php mysql laravel eloquent laravel-5.3

所以我有以下查询:

$a = Model::where('code', '=', $code)
    ->where('col_a', '=' , 1)
    ->orderBy(DB::raw('FIELD(layout, "normal", "split", "flip", "double-faced", "") ASC, layout'))

$b = Model::where('code', '=', $code)
    ->where('col_b', '=' , 1)
    ->orderBy(DB::raw('FIELD(layout, "normal", "split", "flip", "double-faced", "") ASC, layout'))

$a->union($b)->get();

当我先orderBy()"然后联合时,不会发生排序.

No sorting is happening when I 'orderBy()' first and then union.

当我单独查询 '$a' 或 '$b' 时,'orderBy()' 工作正常.

When I do query '$a' or '$b' individually the 'orderBy()' works fine.

当我按照以下方式进行时,orderBy()"会作为一个整体发生.

When I do it in the following way 'orderBy()' happens as a whole.

$a->union($b)
    ->orderBy(DB::raw('FIELD(layout, "normal", "split", "flip", "double-faced", "") ASC, layout'))
    ->get();

我怎样才能使orderBy()"分别适用于每个人,然后将结果合并回来?看起来它应该可以工作.

How can I make it so the 'orderBy()' applies for each individually and then union the results back? It seems like it should work.

如果有人能提供一种方法来做到这一点,即使它是普通的 MySQL,我也会选择你的作为答案,因为我认为 Eloquent 可能存在错误.

If anyone can provide a way to do this, even if it's normal MySQL, I will choose yours as the answer as I think there may be a bug with Eloquent.

推荐答案

尝试以下操作:

$a = Model::where('code', '=', $code)
->where('col_a', '=' , 1);

$b = Model::where('code', '=', $code)->where('col_b', '=' , 1)
->union($a)
->get();

$result = $b;

相关文章