【问题标题】:Is there a way to take x where?有没有办法把 x 带到哪里?
【发布时间】:2021-10-21 02:33:08
【问题描述】:

我要做的是在 booltrue 的地方取 5,在 boolfalse 的地方取 5 em> 并在 bool

上对它们进行排序
|# | Name  | Bool  |
|01| Test1 | true  |
|02| Test2 | false |
|03| Test3 | true  |
|04| Test4 | true  |
|xx| etc...

不要这样做:

$boolTrue  = Test::where('bool', true)->get();
$boolFalse = Test::where('bool', false)->get();
return $boolFalse->merge($boolTrue)->sortByDesc('bool');

我只想向数据库发出 1 个请求而不是 2 个请求,并且想知道是否 这样的事情是可能的:

// Obviously doesn't work
Test::where('bool', true)->take(5)->where('bool', false)->take(5)->orderBy('bool');

【问题讨论】:

  • 你的意思是unions
  • @RonvanderHeijden 是的!这将回答我的问题!谢谢你!

标签: php mysql laravel eloquent laravel-6


【解决方案1】:

你可以像下面那样做。

$true = Test::where('bool', true); //Model instance
$false = Test::where('bool', false)->union($true); //Second model instance

$groupby = DB::query()->fromSub($false, 'nq')
->orderBy('bool')
->get();

【讨论】:

    【解决方案2】:

    @Ron van der Heijden 就我的问题回复了我。我应该使用unions

    我做了什么:

    $boolTrue = Test::where('bool', true);
    return Test::where('bool', false)->union($boolTrue)->orderByDesc('bool')->get();
    

    这只会触发 1 个查询! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2021-10-27
      • 2011-07-28
      • 2019-09-15
      • 2011-07-30
      • 2021-06-06
      • 2021-12-02
      相关资源
      最近更新 更多