Laravel 中“save()”方法的“非法偏移类型”异常

问题描述 投票:0回答:1

我用 Laravel 和 Eloquent 构建了这个简单的应用程序,它应该连接到本地主机 phpmyAdmin 数据库。 我有这个方法:

public function clickOrderPlateClient($id_client, $id_plate){
        $order = Order::where('id_client', $id_client)
            ->where('id_plate', $id_plate)
            ->first();

        $order->qt = ($order->qt) + 1;
        $order->save();
    }

这应该使我的表“orders”(由类

Order
描述)中的属性“qt”增加 1,该记录对应于已订购给定菜肴的给定客户。

但是我总是收到与

$order->save();
行相对应的“非法偏移类型”错误。

错误

这是我的

Order
课程:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table ='orders';
    protected $primaryKey = ['id_client','id_plate'];
    public $timestamps = false;
    public $incrementing = false;

    public function getClient(){
        return $this->belongsTo('App\Models\Client','id_client');
    }

    public function getPlate(){
        return $this->belongsTo('App\Models\Plates','id_plate');
    }
}

php laravel eloquent laravel-8 eloquent-relationship
1个回答
0
投票

模型中不能有两个主键。

尝试使用“复合键”

解决方案1:

带图书馆:

composer 命令来安装库

composer require thiagoprz/eloquent-composite-key

型号代码:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Thiagoprz\EloquentCompositeKey\HasCompositePrimaryKey;
class Order extends Model
{
    use HasCompositePrimaryKey;
    protected $table ='orders';
    protected $primaryKey = ['id_client','id_plate'];
    public $timestamps = false;
    public $incrementing = false;
    public function getClient(){
        return $this->belongsTo('App\Models\Client','id_client');
    }
    public function getPlate(){
        return $this->belongsTo('App\Models\Plates','id_plate');
    }
}

请在此处查看参考:Laravel:使用复合键

解决方案2:

无需安装任何库:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table ='orders';
    protected $primaryKey = 'composite_key';
    public $timestamps = false;
    public $incrementing = false;

    public function getClient(){
        return $this->belongsTo('App\Models\Client', 'id_client');
    }

    public function getPlate(){
        return $this->belongsTo('App\Models\Plates', 'id_plate');
    }

    // Define the composite key attribute
    public function getCompositeKeyAttribute()
    {
        return $this->id_client . '-' . $this->id_plate;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.