繁体   English   中英

通过将查询的结果放入foreach中的另一个查询来从Laravel获取结果

[英]Get results from Laravel by putting the results from the query into another query in foreach

我想通过将查询的结果放入foreach的另一个查询中来从Laravel获取结果。

$first = DB::connection('store')
->table('entire_store')
->select('name', 'code', 'category', 'direct')
->where('open', 'Y')
->get();

第一个查询获取点的信息并将其处理为数组。

将分支机构的信息与员工表中的工作场所进行匹配。

我想一起保存员工的工作场所信息。

$temp = array();    
$i =0;    
foreach($first as $key => $item){

    $temp[$i]['name'] = $item->name;
    $temp[$i]['code'] = $item->code;

    $temp[$i]['category'] = $item->category;
    $temp[$i]['direct'] = $item→direct;

    $second = DB::connection('store')
     ->table('entire_employer')
     ->SELECT('mgr_no','mgr_id', 'status')
     ->where('store',$item->code)->get();
    //I tried.
    foreach($second as $key2 => $item2){
        $temp[$i]['mgr_id'] = $item2->mgr_id;
    }
    $i++;

}

我想将此查询中的值存储在temp_array中。

如果尝试保存第二个查询的值并打印temp_array()的值,则会出现错误。

我还需要检查temp_array()吗?

您要尝试的是将entire_employer表的LEFT JOIN entire_employerentire_store表中。 这将完全按照您在代码中的意图进行操作:将一个表的记录与另一个表的记录进行匹配; LEFT entire_store会将这些记录锚定在主表中(在本例中为entire_store )。

您可以在单个查询中执行此操作,如下所示:

$data = DB::connection('store')
  ->table('entire_store')
  ->select(
      'entire_store.name', 
      'entire_store.code', 
      'entire_store.category', 
      'entire_store.direct', 
      'entire_employer.mgr_no', 
      'entire_employer.mgr_id', 
      'entire_employer.status'
  )
  ->leftJoin('entire_employer', 'entire_employer.store', '=', 'entire_store.id')
  ->where('entire_employer.open', 'Y')
  ->get();

您可以在此处阅读有关联接的更多信息: https : //www.sitepoint.com/understanding-sql-joins-mysql-database/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM