[Laravel 8.x] Model 多主鍵時的調整

一、使用

  1. use 載入 HasCompositePrimaryKey 程式
  2. primaryKey 用陣列的方式寫入
  3. incrementing 設成 false
  1. <?php
  2.  
  3. namespace App;
  4.  
  5. use App\Traits\HasCompositePrimaryKey;
  6. use Illuminate\Database\Eloquent\Model;
  7.  
  8. class ModelName extends Model
  9. {
  10. use HasCompositePrimaryKey;
  11.  
  12. protected $primaryKey = ['key1', 'key2'];
  13. public $incrementing = false;
  14. }

二、HasCompositePrimaryKey 程式

  1. <?php
  2.  
  3. namespace App\Traits;
  4.  
  5. use Illuminate\Database\Eloquent\Builder;
  6.  
  7. trait HasCompositePrimaryKey
  8. {
  9. /**
  10. * Set the keys for a save update query.
  11. *
  12. * @param \Illuminate\Database\Eloquent\Builder $query
  13. * @return \Illuminate\Database\Eloquent\Builder
  14. */
  15. protected function setKeysForSaveQuery(Builder $query)
  16. {
  17. $keys = $this->getKeyName();
  18. if (!is_array($keys)) {
  19. return parent::setKeysForSaveQuery($query);
  20. }
  21.  
  22. foreach ($keys as $keyName) {
  23. $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
  24. }
  25.  
  26. return $query;
  27. }
  28.  
  29. /**
  30. * Get the primary key value for a save query.
  31. *
  32. * @param mixed $keyName
  33. * @return mixed
  34. */
  35. protected function getKeyForSaveQuery($keyName = null)
  36. {
  37. if (is_null($keyName)) {
  38. $keyName = $this->getKeyName();
  39. }
  40.  
  41. if (isset($this->original[$keyName])) {
  42. return $this->original[$keyName];
  43. }
  44.  
  45. return $this->getAttribute($keyName);
  46. }
  47. }

留言