一、使用
- use 載入 HasCompositePrimaryKey 程式
- primaryKey 用陣列的方式寫入
- incrementing 設成 false
- <?php
-
- namespace App;
-
- use App\Traits\HasCompositePrimaryKey;
- use Illuminate\Database\Eloquent\Model;
-
- class ModelName extends Model
- {
- use HasCompositePrimaryKey;
-
- protected $primaryKey = ['key1', 'key2'];
- public $incrementing = false;
- }
二、HasCompositePrimaryKey 程式
- <?php
-
- namespace App\Traits;
-
- use Illuminate\Database\Eloquent\Builder;
-
- trait HasCompositePrimaryKey
- {
- /**
- * Set the keys for a save update query.
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @return \Illuminate\Database\Eloquent\Builder
- */
- protected function setKeysForSaveQuery(Builder $query)
- {
- $keys = $this->getKeyName();
- if (!is_array($keys)) {
- return parent::setKeysForSaveQuery($query);
- }
-
- foreach ($keys as $keyName) {
- $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
- }
-
- return $query;
- }
-
- /**
- * Get the primary key value for a save query.
- *
- * @param mixed $keyName
- * @return mixed
- */
- protected function getKeyForSaveQuery($keyName = null)
- {
- if (is_null($keyName)) {
- $keyName = $this->getKeyName();
- }
-
- if (isset($this->original[$keyName])) {
- return $this->original[$keyName];
- }
-
- return $this->getAttribute($keyName);
- }
- }
留言
張貼留言