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?
My Primary Key: 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?
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.
I have found the solution. In the model, add primaryKey variable and the following function
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With