Reputation: 9199
I am trying to update records in the database table if record already exists. Insert new record if record is not to the database table.
I have written below code for that
DB::enableQueryLog();
$user->userCommission()->save(new UserCommission($input['commission']));
dd(DB::getQueryLog());
when EnableQueryLog it's always show insert query, If record is already in the table.
Here is my query..
array:1 [▼
0 => array:3 [▼
"query" => "insert into `user_commissions` (`created_by`, `status_id`, `percent`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?)"
"bindings" => array:6 [▼
0 => "1"
1 => "1"
2 => "0.10"
3 => 21
4 => "2016-08-13 08:07:45"
5 => "2016-08-13 08:07:45"
]
"time" => 2.57
]
]
In above query user_id 21 record already in the table although Save()
insert record to the database.
where am i wrong with this code? May I have to apply unique key to the table?
Upvotes: 0
Views: 494
Reputation: 1656
There is a alternative one way step to check this.update_at & created_at will be inserted by laravel default
userCommission::updateOrCreate([
'user_id' => 21
],[
'created_by' => 1,
'status_id' => 1,
'percent' => "0.10",
'user_id' => 21,
]);
Upvotes: 0
Reputation: 3957
Require at least one unique column to find or update table record
$userCommission = UserCommission::firstOrNew(array('created_by' => 1));
$userCommission->status_id = 1;
$user()->userCommission()->save($userCommission);
Upvotes: 1