使用foreach循环的Laravel集合迭代

时间:2018-06-08 14:12:34

标签: php laravel collections foreach

order model product model

使用Order模型在控制器中进行简单查询:

$orders = Order::where('user_id', auth()->user()->id)
                        ->orderBy('created_at', 'desc')
                        ->get();
return dd($orders);

dd给出以下结果:(这是正确的)

Collection {#269 ▼
  #items: array:2 [▼
    0 => Order {#270 ▼
      #dates: array:1 [▶]
      #fillable: array:6 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▶]
      #original: array:9 [▶]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
    1 => Order {#271 ▼
      #dates: array:1 [▶]
      #fillable: array:6 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▶]
      #original: array:9 [▶]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
  ]
}

但是当我遍历$ orders集合foreach循环时,只显示第一个数组,第二个数组不可访问... foreach循环有什么问题??

$temp='';
        foreach($orders as $order){
                $temp.= $order->product; // accessing the belongTo method
        }

        dd($temp);

这是输出(只显示一个数组):

"{"id":13,"created_at":"2018-06-06 15:28:21","updated_at":"2018-06-06 18:36:28","type":0,"title":"product 3","description":"this is product no 3 with 5 images","images":"night-product-watch-dramatic-84475_1528310188.jpeg,night-product-watch-dramatic-84475_1528310188.jpeg","alive":1,"user_id":1,"deleted_at":null} ◀"

2 个答案:

答案 0 :(得分:1)

如果要跨所有订单构建产品数组,则无法使用字符串连接。使用数组并将项目推到其上。

$products = [];
foreach ($orders as $order) {
    if ($order->product) {
        $products[] = $order->product;
    }
}
dd($products); // will be an array of all other products.

答案 1 :(得分:0)

试试这个:

$temp= [];
foreach($orders->all() as $order){
     $temp[] = $order->product;
}

您可以编辑您的查询

$orders = Order::where('user_id', auth()->user()->id)
                    ->with('products')
                    ->orderBy('created_at', 'desc')
                    ->get();