• Laravel中定义复合主键


    laravel默认主键是id,但有的时候我们建表时可能会需要用到复合主键,那么laravel中使用Eloquent Medel如何定义复合主键呢?直接上代码。

    首先在app目录先创建文件 Traits/HasCompositePrimaryKey 内容如下:

    // Adjust this to match your model namespace!
    namespace AppTraits;
    
    use IlluminateDatabaseEloquentBuilder;
    
    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  IlluminateDatabaseEloquentBuilder $query
         * @return IlluminateDatabaseEloquentBuilder
         */
        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 IlluminateDatabaseEloquentModel;
    
        class Goods extends Model
        {
            use AppTraitsHasCompositePrimaryKey;
    
            protected $primaryKey = ['param1', 'param2']; //设置组合主键
    
            // coding
    
        }

    这样Eloquent ORM的save()方法就可以使用了。

  • 相关阅读:
    .Net 多线程小结
    VIM 入门操作
    C语言中的数据
    对scanf和printf的研究!!
    C语言常用的编程规范
    ORACLE GOLDEN GATE oracle同步数据至kafka
    mysql5.7关于使用到OR是否会用到索引并提高查询效率的探讨
    sysbench安装
    percona数据库监控工具的安装部署
    redhat6 快速部署percona
  • 原文地址:https://www.cnblogs.com/jdwang-admin/p/8031635.html
Copyright © 2020-2023  润新知