gpt4 book ai didi

php - Laravel 5.6 无法使用 save() 函数将数据保存到具有复合主键的模型中

转载 作者:行者123 更新时间:2023-11-29 05:55:26 24 4
gpt4 key购买 nike

我在 Stackoverflow 上发现了几个关于这个问题的问题,但很多修复都与旧的 Laravel 版本有关,并且似乎不适用于 Laravel 5.6。

这是我的模型:

class Meal extends Model
{
protected $primaryKey = ['meal_id', 'branch_id'];
public $incrementing = false;

public function inhouseOrders(){
return $this->belongsToMany('App\InhouseOrder')->withPivot('qty');
}

public function branch(){
return $this->belongsTo('App\Branch');
}
}

这是创建表的迁移:

    Schema::create('meals', function (Blueprint $table) {
$table->string('meal_id')->unique();
$table->decimal('unit_price', 8, 2);
$table->string('branch_id');
$table->foreign('branch_id')->references('branch_id')->on('branches')->onDelete('cascade');
$table->string('name');
$table->string('status');
$table->timestamps();
$table->primary(['meal_id', 'branch_id']);
});

我的 Controller MealsController 中有一个函数,用于更新膳食状态:

public function changeStatus($branch_id, $meal_id){
$meal = $this->meal->where('meal_id', $meal_id)->where('branch_id', $branch_id)->first();
//$this->meal->find([$meal_id, $branch_id]) doesn't work here so I have to chain two where() functions

$meal->status = 'unavailable';
$meal->save();
return redirect()->route('view_meals');
}

$meal->save()Model.php

中的以下函数中抛出 Illegal Offset type 错误
protected function getKeyForSaveQuery()
{
return $this->original[$this->getKeyName()]
?? $this->getKey();
}

编辑忘了说,我尝试了这个问题中提到的修复: Laravel Eloquent CANNOT Save Models with Composite Primary Keys

但它只是给了我一个App\Meal does not exist错误

最佳答案

您可能应该重新考虑您的关系结构,并使用 @devk 提到的膳食和分支机构之间的多对多关系,但这是针对您当前结构的解决方案。

这可能是 hacky,我不确定它是否会在未来给您带来更多麻烦,但在您的 Meal 模型中添加以下覆盖应该适用于您的情况

protected function setKeysForSaveQuery(Builder $query)
{
foreach($this->primaryKey as $pk) {
$query = $query->where($pk, $this->attributes[$pk]);
}
return $query;
}

关于php - Laravel 5.6 无法使用 save() 函数将数据保存到具有复合主键的模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49822385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com