Laravel 5 覆盖 Eloquent 保存方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36386630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:31:29  来源:igfitidea点击:

Laravel 5 Override Eloquent Save Method

laraveleloquent

提问by OrgGila

I have composite primary keys so Laravel's save() method didn't work. Therefore I need to override the save method. For example, my primary key is a composite key consisting of column_a and column_b. Can you give me example how to override the save method and where I put it?

我有复合主键,所以 Laravel 的 save() 方法不起作用。因此我需要覆盖 save 方法。例如,我的主键是由 column_a 和 column_b 组成的复合键。你能举例说明如何覆盖保存方法以及我把它放在哪里吗?

My Primary Key: column_a, column_b

我的主键:column_a、column_b

I've tried the followings:

我尝试了以下方法:

protected function setKeysForSaveQuery(Builder $query)
{
    parent::setKeysForSaveQuery($query);
    $query->where('locale', '=', $this->locale);
    return $query;
}

I found above code, but it causes 500 Internal Server Error even I call a method that only reads value from database. I have set $primaryKey = 'column_a' and 'locale' (inside where) to column_b. I didn't know what $this->locale refers to?

我找到了上面的代码,但即使我调用一个只从数据库读取值的方法,它也会导致 500 Internal Server Error。我已将 $primaryKey = 'column_a' 和 'locale'(在 where 内)设置为 column_b。我不知道 $this->locale 指的是什么?

Here is another way I found, but it failed too

这是我发现的另一种方法,但它也失败了

protected $secondaryKey = 'column_b';
function newQuery()
{
    $query = parent::newQuery();
    $query->where($this->secondaryKey, '=', $this->type);
    return $query;
}

Again, I didn't know what $this->type refers to.

同样,我不知道 $this->type 指的是什么。

回答by OrgGila

I have found the solution. In the model, add primaryKey variable and the following function

我找到了解决办法。在模型中,添加primaryKey变量和如下函数

protected $primaryKey = array('column1','column2');

protected function setKeysForSaveQuery(\Illuminate\Database\Eloquent\Builder $query) {
    if (is_array($this->primaryKey)) {
        foreach ($this->primaryKey as $pk) {
            $query->where($pk, '=', $this->original[$pk]);
        }
        return $query;
    }else{
        return parent::setKeysForSaveQuery($query);
    }
}

Source: https://github.com/laravel/framework/issues/5517#issuecomment-113655441

来源:https: //github.com/laravel/framework/issues/5517#issuecomment-113655441

回答by Alexey Mezenin

You can override it. You can put it in your model, or you can put it in a trait and use this trate in multiple models if you want.

你可以覆盖它。你可以把它放在你的模型中,或者你可以把它放在一个特征中,如果你愿意的话,可以在多个模型中使用这个 trate。

The original save() method is here(line 1449), maybe this will help.

原来的 save() 方法在这里(第 1449 行),也许这会有所帮助。