laravel - 如何在 Laravel 中手动设置主键值
问题描述
我正在尝试在 Laravel 5.6 中手动设置主键值,但在保存记录时它返回 0。这是我的控制器功能代码。
$next = collect(DB::select('SELECT IFNULL(MAX(IFNULL(lvl1,0)),0)+10 AS NEXTVAL FROM coa_lvl1'))->first()->NEXTVAL;
$lvl1_id = new CoaLvl1();
$lvl1_id->lvl1 = $next;
$this->lvl1->create(array_merge($request->all(),['lvl1' => $next , 'lvl1_code' => $request->get('group_id').'/'.$next]));
coa_lvl1 的迁移:
Schema::create('coa_lvl1', function (Blueprint $table) {
$table->tinyInteger('group_id');
$table->integer('lvl1')->unsigned();
$table->tinyInteger('lvl1_code');
$table->string('lvl1_name',300);
$table->integer('created_by')->nullable(false);
$table->timestamp('created_date')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->integer('last_update_by');
$table->timestamp('last_update_date')->default(DB::raw('0 ON UPDATE CURRENT_TIMESTAMP'));
$table->string('active_flag',1)->default('1');
$table->primary('lvl1');
$table->foreign('group_id')
->references('group_id')
->on('coa_group')
->onDelete('cascade');
});
在我的模型中
protected $table = 'coa_lvl1';
protected $primaryKey = 'lvl1';
public $incrementing = false;
protected $blameable = array('created','updated');
protected $fillable = ['group_id','lvl1_code','lvl1_name','active_flag'];
public $timestamps = false;
public function coaGroup()
{
return $this->belongsTo(CoaGroup::class, 'group_id');
}
public function coaLvl1()
{
return $this->hasMany(CoaLvl2::class,'lvl1');
}
$next 是我要设置的 PrimaryKey 值
解决方案
Schema::create('coa_lvl1', function (Blueprint $table) {
$table->tinyInteger('group_id');
$table->integer('lvl1')->primary(); //$table->integer('lvl1')->unsigned();
$table->tinyInteger('lvl1_code');
$table->string('lvl1_name',300);
$table->integer('created_by')->nullable(false);
$table->timestamp('created_date')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->integer('last_update_by');
$table->timestamp('last_update_date')->default(DB::raw('0 ON UPDATE CURRENT_TIMESTAMP'));
$table->string('active_flag',1)->default('1');
$table->foreign('group_id')
->references('group_id')
->on('coa_group')
->onDelete('cascade');
});
我的模型是这样的
protected $table = 'coa_lvl1';
protected $primaryKey = 'lvl1';
public $incrementing = false;
protected $blameable = array('created','updated');
protected $fillable = ['group_id','lvl1_code','lvl1_name','active_flag'];
public $timestamps = false;
public function coaGroup()
{
return $this->belongsTo(CoaGroup::class, 'group_id');
}
public function coaLvl1()
{
return $this->hasMany(CoaLvl2::class,'lvl1');
}
推荐阅读
- amazon-web-services - 是否可以在 AWS 管道中的反应应用程序内引用代码构建中定义的环境变量?
- git - git pull remote 在 linux 中工作,在 windows 中不工作
- python - Python TypeError - 列表索引必须是整数或切片,而不是 str
- c# - 跨地图的寻路 Unity C#
- php - 如何在 PHP 中将此字符串转换为人类可读的 IP 地址?
- python - numba 中两个列表的交集
- r - 使用 R 进行硬币翻转模拟
- mysql - 单个聚合查询与多个并行查询的 MySQL 性能
- google-cloud-platform - 云数据流找不到模型
- javascript - 使用 SweetAlert 创建故事