【问题标题】:Laravel collections iteration with foreach loopLaravel 集合迭代与 foreach 循环
【发布时间】:2018-11-18 15:05:45
【问题描述】:

它是一个使用 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} ◀"

【问题讨论】:

  • 显示模型定义。
  • class Product extends Model { use SoftDeletes; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; Protected $fillable= ['title', 'type', 'description','images','alive']; public function user(){ return $this->belongsTo('App\User'); } public function orders(){ return $this->hasMany('App\Order'); } }
  • class Order extends Model { use SoftDeletes; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; Protected $fillable= ['comments', 'product_id', 'type', 'user_id', 'alive', 'granted']; public function user(){ return $this->belongsTo('App\User'); } public function product(){ return $this->belongsTo('App\Product'); } }
  • 你能用 var_dump($order) 看看第二个订单的输出是什么吗?我的意思是在 foreach 里面
  • Foreach 是正确的,我认为只是你绊倒了 X)

标签: php laravel collections foreach


【解决方案1】:

如果您要跨所有订单构建产品数组,则不能使用字符串连接。使用数组并将项目推送到它上面。

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

【讨论】:

  • 谢谢,但这仍然使第二个数组项为空...这是 dd 的输出...array:2 [▼ 0 => Product {#276 ▶} 1 => null ] 我只是想知道 foreach 循环有什么问题...或者我是这里遗漏了一些东西......
  • 第二项的null 表示Product 未定义。我更新了代码以避免这种情况
  • 这不是问题...我也得到相同的结果,请参阅有问题的dd($temp);。 foreach 循环假设恰好遍历 2 个产品。目前我不知道为什么它成功循环通过第一个但对于第二次迭代它给出了 null ...(两种产品都存在)我认为它与 laravel 集合有关...可能我没有正确地迭代集合...
  • 代码没有变化...到目前为止,我的问题中的代码和您的答案都给出了相同的结果...但都错过了集合中的第二项...这是真正的问题?
【解决方案2】:

试试这个:

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

您可以编辑您的查询

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

【讨论】:

  • $temp[] 代码没有输出,只是空白屏幕,而如果我在查询中使用 with('products') 它会给出错误:调用模型 [App\Order 上的未定义关系 [products] ]。 (关系是按顺序定义的,因为它属于许多产品,而在产品中它有很多订单)...
  • $orders = Order::where('user_id', auth()->user()->id) ->orderBy('created_at', 'desc') ->get(); $temp=[]; foreach($orders as $order){ $temp[]= $order->product; } dd($temp); 给出了相同的输出,只显示第一项,第二项显示空...array:2 [▼ 0 => Product {#276 ▶} 1 => null ]
猜你喜欢
  • 2018-06-20
  • 2013-10-16
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2018-05-13
  • 2015-02-16
  • 1970-01-01
相关资源
最近更新 更多