Laravel 合并两个查询不会返回所有可用记录

Laravel 合并两个查询不会返回所有可用记录,laravel,Laravel,我很难将两个查询结果合并到一个数组中-合并后的输出包含其中一个查询的所有记录($factsheets),但仅包含其他($actives)的最后一个记录,其中通常至少有3条记录“可用”可返回 我的控制器代码如下: public function show($pest) { $theactives = self::getActives($pest); $thefactsheets = self::getFactsheets($pest); $merged = $theactives-&

我很难将两个查询结果合并到一个数组中-合并后的输出包含其中一个查询的所有记录($factsheets),但仅包含其他($actives)的最后一个记录,其中通常至少有3条记录“可用”可返回

我的控制器代码如下:

public function show($pest)
{
  $theactives = self::getActives($pest);
  $thefactsheets = self::getFactsheets($pest);

  $merged = $theactives->merge($thefactsheets);
  $result = $merged->all();
  return $result;
}

public function getActives($pest){
  $actives = Active::where('pests.id',$pest)
    ->join("active_pest","actives.id","=","active_pest.active_id")
    ->join("pests","pests.id","=","active_pest.pest_id")
    ->select('ai', 'groupcode', 'risk', 'pest')
    ->orderBy('ai')
    ->get();
  return $actives;
}

public function getFactsheets($pest){
  $factsheets = Factsheet::where('pest_id',$pest)
    ->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
    ->select('title', 'factsheets.id')
    ->orderBy('title')
    ->get();
  return $factsheets;
}

同样,我的期望超出了我的能力-我做错了什么?

您不能合并结果集的对象。因此,在合并之前,必须先将结果转换为数组。试试下面的脚本

public function show($pest)
{
  $theactives = self::getActives($pest);
  $thefactsheets = self::getFactsheets($pest);

  return array_merge($theactives, $thefactsheets);
}

public function getActives($pest){
  return Active::where('pests.id',$pest)
    ->join("active_pest","actives.id","=","active_pest.active_id")
    ->join("pests","pests.id","=","active_pest.pest_id")
    ->select('ai', 'groupcode', 'risk', 'pest')
    ->orderBy('ai')
    ->get()->toArray();
}

public function getFactsheets($pest){
  return  Factsheet::where('pest_id',$pest)
    ->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
    ->select('title', 'factsheets.id')
    ->orderBy('title')
    ->get()->toArray();
}

您可以在laravel中使用union

范例

$silver=DB::table(“产品银”)
->选择(“产品名称”
,“产品/银.价格”
“产品数量”;
$gold=DB::表格(“产品黄金”)
->选择(“产品名称”
,“产品/黄金价格”
,“产品/黄金数量”)
->工会(银币)
->get();
然后
dd(黄金);

感谢您的回复。但是,在我的情况下,两个选择中的列数不同会导致错误(基数冲突)。感谢Narayan提供了解决方案。非常感谢。