Laravel中定義複合主鍵

laravel默認主鍵是id,但有的時候咱們建表時可能會須要用到複合主鍵,那麼laravel中使用Eloquent Medel如何定義複合主鍵呢?直接上代碼。php

首先在app目錄先建立文件 Traits/HasCompositePrimaryKey 內容以下:laravel

// 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中使用:app

<?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Goods extends Model
    {
        use \App\Traits\HasCompositePrimaryKey;

        protected $primaryKey = ['param1', 'param2']; //設置組合主鍵

        // coding

    }

這樣Eloquent ORM的save()方法就能夠使用了。ui

相關文章
相關標籤/搜索