laravel默認主鍵是id,但有的時候我們建表時可能會需要用到復合主鍵,那么laravel中使用Eloquent Medel如何定義復合主鍵呢?直接上代碼。
首先在app目錄先創建文件 Traits/HasCompositePrimaryKey 內容如下:
// Adjust this to match your model namespace! namespace App\Traits; use Illuminate\Database\Eloquent\Builder; trait HasCompositePrimaryKey { /** * Get the value indicating whether the IDs are incrementing. * * @return bool */ public function getIncrementing() { return false; } /** * 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->getKeyName() as $key) { if ($this->$key) $query->where($key, '=', $this->$key); else throw new Exception(__METHOD__ . 'Missing part of the primary key: ' . $key); } return $query; } }
在model中使用:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Goods extends Model { use \App\Traits\HasCompositePrimaryKey; protected $primaryKey = ['param1', 'param2']; //設置組合主鍵 // coding }
這樣Eloquent ORM的save()方法就可以使用了。