我在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']);
});
我的控制器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()
在Illegal Offset type
Model.php
错误
protected function getKeyForSaveQuery()
{
return $this->original[$this->getKeyName()]
?? $this->getKey();
}
EDIT 忘了提,我尝试了这个问题中提到的修复: Laravel Eloquent CANNOT Save Models with Composite Primary Keys
但它只是给了我一个App\Meal does not exist
错误
答案 0 :(得分:1)
你可能应该重新考虑你的人际关系结构,并在@devk提到的用餐和分支之间使用多对多的关系, 但这是解决当前结构的问题。
它可能是hacky,我不确定它是否会在将来给你带来更多麻烦,但在你的Meal模型中添加以下覆盖应该适用于你的情况
protected function setKeysForSaveQuery(Builder $query)
{
foreach($this->primaryKey as $pk) {
$query = $query->where($pk, $this->attributes[$pk]);
}
return $query;
}