首页 > 解决方案 > 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');
    }

标签: laraveleloquentone-to-many

解决方案


您正在收集产品,并试图获得它的关税,这就是它抛出错误的原因,这是解决方案


$product = 'smartphone';
$products = Produit::where('designation', $product)->get();
foreach($products as $prod){
   foreach($prod->tarifs as $tarif){
       $tarif->prixAchat = $prix[$id];
       $tarif->save();
   }
}


推荐阅读