雄辩的复合主键 [英] Composite primary key with Eloquent
本文介绍了雄辩的复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们要使用口才的ORM和Laravel 5为 http://www.mbarendezvous.com/来实现Composite主键我知道Eloquent目前不支持它。
请提出相同的最佳选择。
We want to implement Composite primary key with Eloquent ORM and Laravel 5 for http://www.mbarendezvous.com/ I understand it is not currently supported by Eloquent . Please suggest what should be the best alternative for the same.
推荐答案
我使用以下代码。它会覆盖原始的Model.php方法,并考虑所有主键。将其放入使用复合主键的模型中:
I use the following code. It overwrites the original Model.php methods and takes all the primary keys into consideration. Put this into that model that uses a composite primary key:
protected function getKeyForSaveQuery()
{
$primaryKeyForSaveQuery = array(count($this->primaryKey));
foreach ($this->primaryKey as $i => $pKey) {
$primaryKeyForSaveQuery[$i] = isset($this->original[$this->getKeyName()[$i]])
? $this->original[$this->getKeyName()[$i]]
: $this->getAttribute($this->getKeyName()[$i]);
}
return $primaryKeyForSaveQuery;
}
/**
* Set the keys for a save update query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
foreach ($this->primaryKey as $i => $pKey) {
$query->where($this->getKeyName()[$i], '=', $this->getKeyForSaveQuery()[$i]);
}
return $query;
}
编辑:
不要忘记在模型中添加以下内容类,否则将无法正常工作。
Do not forget to add the following in your model class, otherwise this won't work.
public $incrementing = false;
这篇关于雄辩的复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文