Подтвердить что ты не робот

Обновление модели Laravel с двумя первичными ключами

Я пытаюсь обновить модель с двумя первичными ключами.

Модель   

namespace App;

use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    /**
     * The table associated with the model.
     */
    protected $table = 'inventories';

    /**
     * Indicates model primary keys.
     */
    protected $primaryKey = ['user_id', 'stock_id'];
...

Миграция

Schema::create('inventories', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->integer('stock_id')->unsigned();
    $table->bigInteger('quantity');

    $table->primary(['user_id', 'stock_id']);

    $table->foreign('user_id')->references('id')->on('users')
        ->onUpdate('restrict')
        ->onDelete('cascade');
    $table->foreign('stock_id')->references('id')->on('stocks')
        ->onUpdate('restrict')
        ->onDelete('cascade');
});

Это код, который должен обновлять модель инвентаризации, но это не так.

$inventory = Inventory::where('user_id', $user->id)->where('stock_id', $order->stock->id)->first();
$inventory->quantity += $order->quantity;
$inventory->save();

Я получаю эту ошибку:

Illegal offset type

Я также попытался использовать метод updateOrCreate(). Он не работает (я получаю ту же ошибку).

Может ли кто-нибудь сказать, как должна обновляться модель с двумя первичными ключами?

4b9b3361

Ответ 1

Я столкнулся с этой проблемой пару раз. Вам необходимо переопределить некоторые свойства:

protected $primaryKey = ['user_id', 'stock_id'];
public $incrementing = false;

и методы (кредит):

/**
 * Set the keys for a save update query.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
protected function setKeysForSaveQuery(Builder $query)
{
    $keys = $this->getKeyName();
    if(!is_array($keys)){
        return parent::setKeysForSaveQuery($query);
    }

    foreach($keys as $keyName){
        $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
    }

    return $query;
}

/**
 * Get the primary key value for a save query.
 *
 * @param mixed $keyName
 * @return mixed
 */
protected function getKeyForSaveQuery($keyName = null)
{
    if(is_null($keyName)){
        $keyName = $this->getKeyName();
    }

    if (isset($this->original[$keyName])) {
        return $this->original[$keyName];
    }

    return $this->getAttribute($keyName);
}

Помните, что этот код должен ссылаться на класс Eloquent Builder с

use Illuminate\Database\Eloquent\Builder;

Я предлагаю поместить эти методы в HasCompositePrimaryKey чтобы вы могли просто use ее в любой из ваших моделей, которые в ней нуждаются.

Ответ 2

Я решил это, добавив инкремент id и изменив праймериз на uniques.

Schema::create('inventories', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('stock_id')->unsigned();
    $table->bigInteger('quantity');

    $table->unique(['user_id', 'stock_id']);

    $table->foreign('user_id')->references('id')->on('users')
        ->onUpdate('restrict')
        ->onDelete('cascade');
    $table->foreign('stock_id')->references('id')->on('stocks')
        ->onUpdate('restrict')
        ->onDelete('cascade');
});

Кроме того, я удалил из Model

protected $primaryKey = ['user_id', 'stock_id'];

По-моему, это не лучшее решение.