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

Laravel 5.6 cannot save data into a model with a composite primary key using save() function

我在 Whosebug 上发现了几个关于这个问题的问题,但很多修复都与旧的 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');
    }
}

这是创建 table:

的迁移
    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()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;
}