我们希望使用Eloquent ORM和Laravel 5为http://www.mbarendezvous.com/实现Composite主键我明白Eloquent目前不支持它。 请建议什么应该是相同的最佳选择。
答案 0 :(得分:5)
我使用以下代码。它会覆盖原始的Model.php方法并考虑所有主键。将其放入使用复合主键的模型中:
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;
}
编辑: 不要忘记在模型类中添加以下内容,否则这不会起作用。
public $incrementing = false;
答案 1 :(得分:1)
您可以从laravel的Model类中覆盖setKeysForSaveQuery
方法。您可以将此方法更改为:
/**
* Set the keys for a save update query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
$query->where('secondKeyName', $this->secondKeyName); // <- added line
return $query;
}
答案 2 :(得分:-1)
您可以覆盖扩展具有复合键的Model的类的save()方法,如下所示:
public function save(array $options = array())
{
$query = $this->newQueryWithoutScopes();
// MY MODEL SPECIFIC FIX
$query->where('OTHER_ID', '=', $this->OTHER_ID);
// END MY FIX
// the rest of the standard model->save() code is here but I cut it out for brevity.
// Use what is in Model.php already.
}
我在这里看到了这个解决方案:https://github.com/laravel/framework/issues/5517
答案 3 :(得分:-1)