我正在尝试更新有两个主键的模型。
模型
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() 方法。它不起作用(我得到同样的错误)。
谁能告诉我应该如何更新具有两个主键的模型?
我已经遇到过这个问题好几次了。您需要覆盖一些属性:
protected $primaryKey = ['user_id', 'stock_id'];
public $incrementing = false;
和方法(credit https://github.com/laravel/framework/issues/5355#issuecomment-161376267):
/**
* 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
它适用于任何需要它的模型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)