【问题标题】:Get all elements of array in query laravel获取查询laravel中数组的所有元素
【发布时间】:2017-06-09 13:51:05
【问题描述】:

我正在尝试在一个数组中循环,但是当涉及到查询时,它只获取第一个元素,所以一点帮助将非常重要。

 $data = Offers::whereIn('id_business', $business_id_array)
                    ->where([
                        'visible' => 'yes',
                        'delete' => 'no'
                    ])
                    ->where('end_date', '>=', date('Y-m-d h:m:i'))
                    ->orderBy('id', 'desc')
                    ->get();

                $data=array($data);

                foreach($data as $key => $item) {
                    $offers = DB::select('the data i need to get WHERE o.`id` = ' . $item[$key]['id']);


                }

这是我的问题,它只获取第一个元素的 id

o.`id` = ' . $item[$key]['id']

【问题讨论】:

  • 在你的循环中尝试$item->id
  • @AmitGupta 没有人,它不起作用

标签: php arrays laravel laravel-5


【解决方案1】:

因为您在 foreach 循环中返回了视图,所以它只循环通过第一项并返回。你可以用这种情况做的是

$data = Offers::whereIn('id_business', $business_id_array)...->get()->toArray();
$offers = array_map(function($item){
     $offer = DB::select('the data i need to get WHERE o.`id` = ?', [$item->id]);  
     return $offer;
},$data);
return view(....,['offers' =>$offers]);

【讨论】:

    【解决方案2】:

    首先,您不需要将$data 强制转换为数组 - 它将作为一个集合返回,您可以像数组一样对其进行迭代。这样你就可以使用这样的东西了

    $offers = Offers::whereIn('id_business', $business_id_array)...->get();
    
    foreach ($offers as $offer) {
        $moreData = DB::select('the data i need to get WHERE o.`id` = ?', [$offer->id]);
    }
    

    【讨论】:

    • 它仍然只有一个 id,只有第一个,而我得到 4 个元素作为数组
    • 改用foreach ($offers->items as $offer)
    • @ayip 你的意思是 foreach ($offers as $items=>$offer)
    • 不,使用foreach ($offers->items as $offer) 或者如果它给出任何错误,使用foreach ($offers->getItems() as $offer)
    • @User154584 除了运行查询之外,您对循环内的 $moreData 做了什么吗?
    【解决方案3】:

    这看起来您正在使用一个表中的 id 从另一个表中获取相关数据。

    两个表之间不应该存在关系吗?

    @Chris G 的答案看起来是正确的,也许 dd($offers) 可以确定里面有什么。

    米克

    【讨论】:

    • 这样得到一个数组: Collection {#256 ▼ #items: array:4 [▼ 0 => Offers {#255 ▶} 1 => Offers {#254 ▶} 2 =>优惠 {#253 ▶} 3 => 优惠 {#252 ▶} ] }
    • 在每个数组中我需要获取 ID
    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多