Composite Primary key with Laravel


Posted on 2015-04-14 18:18:26

Hi ! I'm newbie with Laravel. Recently I try to make some simple web application with Laravel 5.0 but it's very hard to work with model that has composite primary key. Exp : primary key (user_id,item_id) It seems that there is no way  to update, delete correctly if using model function (save(), delete(),..) I try 1 way to avoid problem and it works. Here is my solution :

1. Make class call BaseModel and every model that you want to use composite primary key has to extend from BaseModel instead of model. 2. BaseModel extends Model 3. Create attribute call secondaryKey , thirdKey,....etc to hold your composite primary key. 4. Override function setKeysForSaveQuery(Builder $query) {} Here is my full code :

use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder;

class BaseModel extends Model {

protected $secondaryKey = NULL; public function __construct() { parent::__construct(); }

public function setKeysForSaveQuery(Builder $query) { $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()); if(isset($this->secondaryKey)) { $query->where($this->secondaryKey, '=', $this->getAttribute($this->secondaryKey)); } return $query; }