Reputation: 185
I am Trying to set Primary Key Value Manually in Laravel 5.6 but it return 0 when record save. Here is my code of Controller Function.
$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]));
Migration For 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');
});
And in my Model
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 is my PrimaryKey Value that I am trying to set
Upvotes: 1
Views: 1925
Reputation: 185
I have done this by adding primarykey in protected
$fillable = ['lvl1','group_id','lvl1_code','lvl1_name','active_flag'];
I think its not right way but its working for me
Upvotes: 0
Reputation: 501
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');
});
My Model is like This
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');
}
Upvotes: 1