具有两个主键的Laravel模型更新

具有两个主键的Laravel模型更新,第1张

具有两个主键的Laravel模型更新

我已经遇到过几次这个问题。您需要覆盖一些属性:

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

方法功劳):

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;}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 IlluminateDatabaseEloquentBuilder;

我建议将这些方法放入

HasCompositePrimaryKey
Trait中,以便您可以
use
在需要它的任何模型中使用它。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5441417.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存