[英]can I use eloquent model in foreach loop
foreach ($rows as $row) {
$source = Inventory_sources::where('code', $row['inventory_source_code'])->first();
$source_id=$source->id;
$product = Product::create([
'type' => $row['type'],
'sku' => $row['sku'],
'attribute_family_id' => $row['attribute_family'],
]);
product_flat::create([
'product_id' => $product->id,
'sku' => $row['sku'],
'name' => $row['name'],
'price' => $row['price'],
'status' => $row['status'],
]);
product_inventories::create([
'inventory_source_id' => $source_id,
'product_id' => $product->id,
'qty' => $row['qty'],
]);
}
error - Trying to get property 'id' of non-object I try dd() its show the output.错误 -试图获取非对象的属性“id”我尝试 dd() 它显示 output。 how to resolve this issue如何解决这个问题
your problem is that the $source variable could be sometimes null,你的问题是 $source 变量有时可能是 null,
you must avoid use $source->id;你必须避免使用 $source->id; when the $source is null当 $source 是 null
$source = Inventory_sources::where('code',
$row['inventory_source_code'])->first();
if($source!=null)
{
// write the suitable code here ...
}
This error you're getting because while add condition code
= $row['inventory_source_code']
sometime you're not getting records.您收到此错误是因为在添加条件code
= $row['inventory_source_code']
时有时您没有获取记录。
So you need to check the condition.所以你需要检查条件。
foreach ($rows as $row) {
$source = Inventory_sources::where('code', $row['inventory_source_code'])->first();
if(!empty($source)){
$source_id=$source->id;
//your entire logic.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.