jeudi 31 mars 2016

Laravel Model with Two Primary Keys update

I'm trying to update Model which has two primary keys.

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

Migration

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

This is code which should update Inventory model, but it doesn't.

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

I get this error:

Illegal offset type

I also tried to use updateOrCreate() method. It doesn't work (I get same error).

Can anyone tell how Model with two primary key should be updated?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire