[英]Looping through array
我有一个像这样的数组:
我的问题是如何遍历对象。 我想将这些都关联到一个容器。
所以我尝试了这个:
foreach ($data['plates'] as $index => $element) {
//Don't worry about the container_id.
$plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
}
但是似乎无法正常工作。 有什么想法我在做错或遗漏吗?
仅供参考—模型之间的关系
平板型号
public function plateContainer()
{
return $this->belongsTo('App\Models\PlateContainer');
}
PlateContainer模型
public function plates()
{
return $this->hasMany('App\Models\Plate');
}
更新#1:提交简单表单后,数组来自AngularJS。 抱歉忘了提这个。
更新#2:好的。 我尝试了以下方法。
foreach ($data['plates'] as $element)
{
foreach ($element as $value)
{
$plates = Plate::find($value)->plateContainer()->associate($data['container_id'])->save();
}
}
…但仍然无法正常工作。 检查数据库,它仅显示使用给定容器更新了第一块板。
我尝试了dd($value);
只显示1
您的$data['plates']
包含2个关联数组:[0] => {etc ...}和[1] => {etc ...}。 因此,您需要一个嵌套循环。
for ($i=0; $i<count($data['plates']); $i++) {
foreach ($data['plates'][$i] as $index => $element) {
//Don't worry about the container_id.
$plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
}
}
出事了。
foreach ($data['plates'] as $index => $element) {
$plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
}
绝招
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.