【发布时间】:2016-07-19 19:47:13
【问题描述】:
我正在尝试更新具有两个主键的模型。
型号
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 = Inventory::where('user_id', $user->id)->where('stock_id', $order->stock->id)->first();
$inventory->quantity += $order->quantity;
$inventory->save();
我收到此错误:
Illegal offset type
我也尝试使用 updateOrCreate() 方法。它不起作用(我得到同样的错误)。
谁能告诉我们应该如何更新具有两个主键的模型?
【问题讨论】:
-
非法偏移类型,哪种类型?有行号吗?此查询中是否存在库存?
-
在 laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php 第 2762 行出现 ErrorException。` /** * 获取 casts 数组。 * * @return array */ public function getCasts() { if ($this->getIncrementing()) { return array_merge([ $this->getKeyName() => 'int', // line 2762 ], $this- >铸件); } 返回 $this->casts; } ` 顺便说一下,这个库存存在。
-
粘贴完整的错误信息,以便我们可以在上下文中查看整个消息。
-
勾选这个github.com/laravel/framework/issues/5517 Laravel eloquent 不支持复合主键。 (旁注,您不能有两个主键。两个字段都是唯一主键的一部分)
标签: php laravel laravel-5 eloquent composite-primary-key