Last active
June 1, 2018 03:24
-
-
Save janzikmund/84df3c59cffe073a8cad3922e88295ff to your computer and use it in GitHub Desktop.
Allow composite key for eloquent model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ContentBlock::updateOrCreate([ | |
'alias' => $key, | |
'section' => $section_snake, | |
], [ | |
'content' => $val, | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\Eloquent\Builder; | |
class ContentBlock extends Model | |
{ | |
// if set it doesn't allow keyBy() called on collection. And still the key is composite so we have to search by two params manually anyway | |
//protected $primaryKey = 'alias'; | |
protected $fillable = ['content', 'alias', 'section']; | |
/** | |
* Set the composite keys for a save update query. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $query | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
protected function setKeysForSaveQuery(Builder $query) | |
{ | |
$query | |
->where('alias', '=', $this->getAttribute('alias')) | |
->where('section', '=', $this->getAttribute('section')); | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment