在 Laravel 中,具有多个主键的表在建模时可能会带来挑战。默认情况下,Laravel 模型假设有一个名为“id”的主键。
要处理复合主键(多列唯一定义表行),我们需要自定义模型。但是,使用数组或逗号分隔的字符串来定义主键在 Model.php 中不起作用。
此限制的解决方案是使用以下特征:
namespace App\Model\Traits; // *** Adjust namespace to match your models *** use Illuminate\Database\Eloquent\Builder; trait HasCompositePrimaryKey { /** * Indicates if IDs are incrementing. * * @return bool */ public function getIncrementing() { return false; // Composite keys are not incrementing. } /** * Set 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) { // Add if isset() if (isset($this->$key)) { $query->where($key, '=', $this->$key); } else { throw new Exception('Missing part of primary key: ' . $key); } } return $query; } /** * Execute query for a single record by ID. * * @param array $ids Array of keys, like [column => value]. * @param array $columns * @return mixed|static */ public static function find($ids, $columns = ['*']) { $me = new self; $query = $me->newQuery(); foreach ($me->getKeyName() as $key) { $query->where($key, '=', $ids[$key]); } return $query->first($columns); } }
将特质放入你的模型的“Traits”目录并将其添加到具有复合键的任何模型中:
class MyModel extends Eloquent { use Traits\HasCompositePrimaryKey; // *** Use the trait *** /** * The primary key of the table. * * @var string */ protected $primaryKey = ['key1', 'key2']; ... }
以上是如何在 Laravel 5 模型中定义和使用复合主键?的详细内容。更多信息请关注PHP中文网其他相关文章!