【问题标题】:Laravel 5.2 Update with foreign keyLaravel 5.2 使用外键更新
【发布时间】:2024-01-18 18:18:02
【问题描述】:

你好,我最近一直在做一个 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

如果有任何信息丢失,请告诉我,我会补充的

【问题讨论】:

  • 你使用什么样的关系?根据关系的类型,最好使用 save()、attach()、sync() 或 associate() 等函数。 doc.
  • 表之间的关系是BelongsTo
  • 能否请您发布您的模特关系?
  • 我已经编辑了帖子并包含了有关系的模型
  • 外键值作为另一个表的行的标识符(通常包含 PRIMARY KEY)。但是您想用产品数量更新您的外国字段。阅读此*.com/a/5292099/2429040。希望你会有一个清晰的认识:-)

标签: laravel sql-update laravel-5.2


【解决方案1】:

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

$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);

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

【讨论】:

  • 当我将此代码与正确的模型一起使用时,我收到一个错误调用未定义的方法 Illuminate\Database\Query\Builder::voorraad()
  • 你定义了模型的关系吗?您的 Product 和 Location 模型中都需要一个 voorraad() 或 voorraden() 函数。
  • 我需要在 Product 和 location 模型中加入什么雄辩的关系?