laravel - laravel 5.7 with() 方法
问题描述
我正在尝试查询控制器中的两个相关模型,但请求失败。这是我的代码:
$product = 'smartphone';
$prod = Produit::where('designation', $product)->with('tarifs')->get();
foreach($prod->tarifs as $tarif){
$tarif->prixAchat = $prix[$id];
$tarif->save();
}
这是错误消息:此集合实例上不存在属性 [tarifs]。
我在 Produit 模型中有这个:
public function tarifs()
{
return $this->hasMany('App\Models\Tarif');
}
和关税模型:
public function produit()
{
return $this->belongsTo('App\Models\Produit');
}
解决方案
您正在收集产品,并试图获得它的关税,这就是它抛出错误的原因,这是解决方案
$product = 'smartphone';
$products = Produit::where('designation', $product)->get();
foreach($products as $prod){
foreach($prod->tarifs as $tarif){
$tarif->prixAchat = $prix[$id];
$tarif->save();
}
}
推荐阅读
- objective-c - 为什么 NSNumber(s) 的 NSArray 无法解码?
- python - 分解列表中的字典键
- reactjs - ReactJS,useLayoutEffect 与文档,空值
- r - 提取具有高相关性的变量对
- go - Golang Bazel 为空 coverage_report.dat
- amazon-web-services - MWAA - 环境不断加载
- git - 如何使用`GIT_CONFIG`环境变量
- c - 如何在 C 中重新分配/扩展二维数组?
- laravel - 我如何获得数组中的“行”
- java - 如何使用 Gradle 7 在 Spring Boot 应用程序中添加外部 jar 文件依赖项?