2016-11-23 85 views
0

我一直在laravel的一个学校项目上工作,我想能够更新我的数据库中的现有记录,我为它做了一个功能,但是当我点击更新按钮时我的数据库中的Updated_at字段被更新,没有别的,即使我改变编辑表单上的每个属性,我也观看并遵循了Laracasts laravel基础系列,但它给了我相同的结果。Laravel 5.2更新函数

这是我的存储和编辑方法我已经为它

public function update(Request $request, $id) 
    { 
     //$product = Product::findOrFail($id) = finding the Id of the Product i want to update 


     $product = Product::FindorFail($id); 

     // Requesting a update query on the attributes: name , buy price, sell price, and the foreign_key 
     $product->update($request->only(['naam', 'inkoopPrijs', 'verkoopPrijs', 'Fabrieken_Id'])); 

     return redirect(Route('producten.index')); 
    } 

提出这是模型IM uing它。

class Product extends Model 
{ 
    protected $fillable = ['Id', 'naam', 'inkoopPrijs', 'verkoopPrijs', 'Fabrieken_Id', 'updated_at', 'created_at']; 

     protected $table = "producten"; 


    public function fabriek() 
    { 
     return $this->BelongsTo('App\Fabriek', 'Fabrieken_Id'); 
    } 

当我var_dump($产品)喜欢它在上面说只有Updated_at字段更新和没有别的。

如果我需要更多的信息,只是让我知道,我会添加到这个问题

回答

1

更新方法是大规模更新,而不是单个记录的更新,因为这里详述:

https://laravel.com/docs/5.3/eloquent#updates

你需要的是save()它更新一个特定的记录。您可以将它与fill()结合使之从请求数据数组中更新。

public function update(Request $request, $id) 
{ 
    $product = Product::FindorFail($id); 
    $product->fill($request->only(['naam', 'inkoopPrijs', 'verkoopPrijs', 'Fabrieken_Id'])); 
    $product->save(); 

    return redirect(Route('producten.index')); 
} 
0

,你必须这样写:

public function update(Request $request, $id) 
{   
     $product = Product::find($id); 
     $product->name = $request->get('naam'); #naam : name of input field 
     $product->attribute2 = $request->get('inkoopPrijs'); 
     $product->attribute3 = $request->get('verkoopPrijs'); 
     $product->attribute4 = $request->get('Fabrieken_Id'); 

     $product->save(); 
     return redirect(Route('producten.index'));  
} 

或者让你更新的方法,但在您的产品型号中加入这一行 -

protected $fillable = ['name', 'attribute2', 'attribute3', 'attribute4']; 

PS:如果你使用FindOrFail那么你应该使用try catch