Model Laravel z dwoma kluczami głównymi aktualizacja [duplikat]

To pytanie ma już odpowiedź tutaj:

Próbuję zaktualizować Model, który ma dwa podstawowe klucze.

Model

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'];
...

Migracja

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');
});

Jest to kod, który powinien zaktualizować Model inwentaryzacji, ale tak nie jest.

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

I get this błąd:

Illegal offset type

Próbowałem również użyć metody updateOrCreate (). Nie działa (dostaję ten sam błąd).

Czy ktoś może powiedzieć jak należy zaktualizować Model z dwoma kluczami podstawowymi?

Author: alepeino, 2016-03-31

2 answers

Wpadłem na ten problem kilka razy. Musisz nadpisać niektóre właściwości:

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

I metody (kredyt):

/**
 * 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);
}

Proponuję umieścić te metody w HasCompositePrimaryKey cecha więc można po prostu use to w każdym modelu, który tego potrzebuje.

 40
Author: alepeino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-06 15:43:42

Rozwiązałem to dodając zwiększające się id i zmieniając primary na 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');
});

Również usunąłem z modelu

protected $primaryKey = ['user_id', 'stock_id'];
Moim zdaniem nie jest to najlepsze rozwiązanie.
 0
Author: Ugnius Malūkas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-31 12:23:15