【问题标题】:Merge two queries and order them on base of created_at in Laravel合并两个查询并根据 Laravel 中的 created_at 对它们进行排序
【发布时间】:2015-07-05 19:00:29
【问题描述】:

我为两个表创建了模型。现在我想根据created_at执行查询并合并结果。

我的查询是:

    $first  =  RequestF::where('userId','=',$userId)->get();
    $second =  RequestS::where('userId','=',$userId)->get();

我可以使用以下方法合并它们:

     foreach($first as $f) {
        $second->add($f);
     }

但这只是在$second 的末尾添加$first-objects,我无法根据created_at 按顺序获取它们。

如何合并这两个查询并同时对它们进行排序?
谢谢。

更新 在@MargusPala 建议之后,这是我在$second->toArray() 之后的结果,但是奇怪的是一个对象不按顺序排列!!对象编号 10:

{
  "status" : "Success",
  "data" : {
"showcases" : {
  "10" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-22 10:51:25",
    "type" : "F"
  },
  "2" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:14:32",
    "type" : "L"
  },
  "3" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:15:00",
    "type" : "L"
  },
  "11" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:54:56",
    "type" : "F"
  },
  "4" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 11:22:09",
    "type" : "L"
  },
  "5" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-26 10:42:38",
    "type" : "L"
  },
  "6" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:59:03",
    "type" : "L"
  },
  "7" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:59:23",
    "type" : "L"
  },
  "0" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-22 11:26:25",
    "type" : "L"
  },
  "8" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 10:05:19",
    "type" : "L"
  },
  "1" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:13:53",
    "type" : "L"
  },
  "9" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 10:05:33",
    "type" : "L"
  }
}
  },
 "message" : "Here is results"
}

这很奇怪,还有其他事情,我怎样才能得到 JSON 数组而不是 JSON 对象的结果。

【问题讨论】:

  • 试试这个:$first = RequestF::where('userId','=',$userId)->orderBy("created_at", "ASC")->get(); $second = RequestS::where('userId','=',$userId)->orderby("created_at","ASC")->get();
  • @CoolD 我知道,但是合并$first$second 后,第二个查询的对象被添加到第一个查询的末尾,并且没有排序。

标签: php mysql laravel model


【解决方案1】:

Laravel 有 sortBy() 函数,可以让你对集合进行排序。像这样使用它

$second = $second->sortBy(function($s)
{
    return $s->created_at;
});

【讨论】:

  • 这正是我想要的,但是在尝试使用 $second->toArray() 返回响应后,它返回 JSON 对象,而不是 JSON 数组。有什么解决办法吗?
  • 您可以使用dd($second->toArray()) 来查看集合转换为什么以及如何修复它。确保你以后做return $second->toArray();
  • 其实我发现,我的结果没有排序,很奇怪,但是我更新了问题。
猜你喜欢
  • 2022-10-04
  • 1970-01-01
  • 2023-03-18
  • 2016-09-23
  • 2020-08-09
  • 2011-12-30
  • 2011-04-05
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多