Laravel 5.2使用外键更新

时间:2017-03-31 13:40:50

标签: laravel sql-update laravel-5.2

你好我最近一直在做一个laravel项目,我希望能够更新我的记录,其中有外键。我已经成功地更新了没有外键的表中的记录,但出于某种原因,我的带有外键的表并不想更新。当我var_dump($ voorraad)我在屏幕上获得新值但它没有更新到数据库中。我的Product表和Location表有相同的代码,并且它完全正常。

我的控制器:

 public function update(Request $request, $id)
{
    //voorraad = stock in dutch
    //Product_id = foreign key from the table products
    //locatie_Id = foreign key from the tabe locations
    //aantal = ammount of a certain product

    $voorraad = Voorraad::FindOrFail($id);


    $voorraad->fill($request->only('aantal', 'Product_id', 'locatie_Id'));

    $voorraad->save();

    return redirect(route('voorraad.index'));

}

我的voorraad模型

   class Voorraad extends Model
{
    //aantal is the ammount 


protected $fillable = ['aantal', 'Product_id', 'locatie_Id'];
protected $table = 'voorraad';

public function products()
{
    return $this->belongsTo('App\Product', 'Product_id');
}

public function locaties()
{
    return $this->belongsTo('App\Locatie', 'locatie_Id');
}

我的产品型号

class Product extends Model
{
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name


protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','created_at', 'updated_at'];

protected $table = 'product';

}

我的位置模型:

class Locatie extends Model
{
protected $fillable = ['naam'];

protected $table = 'locatie';    
}

我的编辑表单:

    {!! Form::model($voorraad,['action' => ['VoorraadsController@update', $voorraad->Id], 'method' => 'PATCH'])!!}

{!! Form::label('aantal', 'aantal:') !!}
{!! Form::text('aantal')!!}<br>

{!! Form::label('Product_id', 'product:') !!} 
{!! Form::select('Product_id', $products)!!}<br>

{!! Form::label('locatie_Id', 'locatie:') !!} 
{!! Form::select('locatie_Id', $locaties)!!} <br>

{!! Form::submit('edit') !!}

Var_dump的Gyazo($ voorraad):https://gyazo.com/109d54e2bb7a91bbb8b047611e66dbe0

var_dump的gyazo($ request):https://gyazo.com/8437ee90881ba38a039b5b583f8296a5

如果有任何信息丢失,请告诉我,我会添加

1 个答案:

答案 0 :(得分:0)

您可以更新模型并将其与其所属的产品和位置相关联,如下所示:

$voorraad = Voorraad::findOrFail($id); 
$product = Product::findOrFail($request->input('Product_id'));
$location = Location::findOrFail($request->input('locatie_Id'));

$voorraad->aantal = $request->input('aantal');
$voorraad->save();

$product->voorraad()->associate($voorraad);
$location->voorraad()->associate($voorraad);

当然,您必须为模型使用正确的名称。