douchun3680 2018-05-16 00:53
浏览 741
已采纳

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

I want to get results from Laravel by putting the results from the query into another query in foreach.

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

The first query takes the information of the points and processes them into an array.

Match the information of the branches with the workplace in the employee table.

I want to save the workplace information of the employees together.

$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++;

}

I want to store the values from this query in temp_array.

I get an error if I try to save the value of the second query and print the value of temp_array ().

Is there anything more I need to do to check temp_array ()?

  • 写回答

1条回答 默认 最新

  • doujuxin7392 2018-05-16 03:30
    关注

    What you are trying to do is a LEFT JOIN of the entire_employer table onto the entire_store table. That will do exactly what you're trying to do in your code: match the records of one table with the records on the other; a LEFT join will anchor those records in the primary table (entire_store, in this case).

    You can do this in a single query, as such:

    $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();
    

    You can read more about joins here: https://www.sitepoint.com/understanding-sql-joins-mysql-database/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?