Despite having check getting Integrity constraint violation error - php

I'm on laravel 5.2 and I'm checking whether the combo of 3 ids exists or not in DB after that I'm updating or creating the record.
I have the unique key index on first_id, second_id, third_id field. Still, occasionally I'm getting: Integrity constraint violation: 1062 Duplicate entry '103797-5371-D8BTmX0GAi' for key 'first_id'.
public function notification($fId, $sId, $tId)
{
$getEmail = Input::get('email');
$email = new Email($getEmail);
if(!$email->isValid()){
return Response::json(['error_message' => self::ERROR_MESSAGE_INVALID_EMAIL], 422);
}
$searchEmail = DB::table('newsletter')
->select('id', 'status', 'email')
->where(['first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId])
->first();
if($searchEmail){
$updateEmail = DB::table('newsletter')
->where(['first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId])
->update(['email' => $getEmail, 'deleted_at' => NULL, 'status' => 1, 'updated_at' => Carbon::now()]);
if($updateEmail){
return Response::json('Success',201);
}
}else{
$result = DB::table('newsletter')
->insertGetId(['email' => $getEmail, 'first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId]);
if($result){
return Response::json('Success',201);
}
}
}
We have huge traffic and we get an error like this 5-6 times a week. Despite we have a check for record exists or not.
Is that can be DB sync issue? or is it something wrong with the code?

Related

Laravel upsert createing duplicate records

$responsible_users = collect($request->responsible_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::RESPONSIBLE_ROLE]));
$subordinate_users = collect($request->subordinate_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::DIRECT_SUBORDINATE_ROLE]));
$internal_users = $responsible_users->merge($subordinate_users)->toArray();
OrganizationElementUser::upsert($internal_users, ['user_id', 'organization_element_id', 'type'], ['user_id', 'organization_element_id', 'type']);
Why is my upsert creating duplicate records?
My user_id, organization_element_id, type fields can individually be duplicate but all 3 of them combined creates a unique record
ex. of what I want is:
user_id == 1 && organization_element_id == 2 && type == 'test'
//ignore if true otherwise insert
You can use UpdateOrCreate method. Documentation here.
User::updateOrCreate([
'user_id' => $user_id,
'organization_element_id' => 2,
'type' => 'test'], //if everything matches with these conditions, the row will get updated, otherwise, it will be inserted. It is like the where clause.
['column_xyz' => $request->new_string],
);

Retrive Bulk Inserted ids after insert() function in Laravel 6+

I Research a lot but Could not find any solution. So i am posting it Here
My problem is After Inserting bulk rows i want to get all the inserted ids to save the ids to another Pivot table.. Here is my code
$create_market = [];
$create_market_possibility = [];
foreach ($request->type0 as $key => $value) {
array_push($create_market, [
'market_id' => $value['market_id'],
'event_id' => $value['event_id'],
'name' => $value['name'],
'bet_min' => $value['min_bet'],
'bet_max' => $value['max_bet'],
'commission' => $value['commission'],
'type' => 0,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
foreach ($request->type1 as $key => $value1) {
array_push($create_market, [
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'name' => $value1['name'],
'bet_min' => $value1['min_bet'],
'bet_max' => $value1['max_bet'],
'commission' => $value1['commission'],
'type' => 1,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
foreach ($value1['possibility'] as $key => $value2) {
array_push($create_market_possibility, [
// because i am not getting the inserted ids here i cant push it here
// that is the problem i am facing
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'possibility' => $value2['possibility'],
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
}
Market::insert($create_market);
// Here i want to retrive the last inserted all ids and put then in the obj of
[$create_market_possibility] array ...
if(count($create_market_possibility) > 0) {
MarketPossibility::insert($create_market_possibility);
}
$response = [
'status' => true,
'message' => 'Market Successfully Created'
];
return response()->json($response); //# sending response
i did this thing wher i was using create() for single insert
$id = Market::create($array)
It was returning me the object.. But in this case i have to insert multiple rows..
If there any other way to do it please let me know , Thank You!
1. For type0
You can run Market::insert($array) for type0 since there is no associated MarketPossibility
2. For type1,
You will have to create each Market one by one then associate it - you can use saveMany() to make it cleaner a faster:
$market = Market::create([...])
$new_market_possibility = [];
foreach ($value1['possibility'] as $key => $value2) {
$new_market_possibility[] = new App\MarketPossibility([...]);
}
$market->marketPossibilities()->saveMany($new_market_possibilities);
All that assuming that you have standard relations in place between Market and MarketPossibility

What's a way around SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry | Laravel 5.8

Error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'7e88079cec' for key 'unique_email_id'
I'm importing data from an API and storing it into a database.
It works on the first try but doesn't update it. I know why wouldn't a "replace" work? Laravel docs don't seem to have a replaceOrUpdate. Do I have to resort to old SQL queries?
$members = Newsletter::getMembers('subscribers');
foreach($members['members'] as $member)
{
DB::table('newsletter')->where('email', $member['email_address'])->updateOrInsert([
'email' => $member['email_address'],
'unique_email_id' => $member['unique_email_id'],
'web_id' => $member['web_id'],
'status' => $member['status'],
'created_at' => $member['timestamp_opt'],
'updated_at' => $member['last_changed']
]);
}
You can use updateOrCreate on the Eloquent instance instead, like this:
foreach($members['members'] as $member)
{
Newsletter::updateOrCreate(['email' => $member['email_address']],
[
'unique_email_id' => $member['unique_email_id'],
'web_id' => $member['web_id'],
'status' => $member['status'],
'created_at' => $member['timestamp_opt'],
'updated_at' => $member['last_changed']
]);
}
So the first param (array) is used as a where clause, if found it will update if not it will create a new record.

CODEIGNITER how to insert user_ID to mySQL when that user_ID is logged in

this is the error page
Cannot add or update a child row: a foreign key constraint fails (latihan_ci.adventure, CONSTRAINT adventure_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON UPDATE CASCADE)
INSERT INTO adventure (name, category, place, state) VALUES ('semeru', 'gunung', 'asa', 'asd')
and this is my controller
public function addTrip(){
$this->load->model('userModel');
$newTrip = ['name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'place' => $this->input->post('place'),
'state' => $this->input->post('state'),
];
$data['users'] = $this->userModel->getUserId()->result();
$this->db->insert('adventure',$newTrip);
$this->db->insert('adventure',$data);
redirect('userController/profile');
}
and this is my Model
public function getUserId()
{
return $this->db->get('users',['user_id']);
}
so how to add the user_ID to the mySQL when the value is user_ID that is already login..Thanks alot
when you are login at that time user_id store in session after use
controller
$newTrip = ['name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'place' => $this->input->post('place'),
'state' => $this->input->post('state'),
'user_id'=>$this->session->userdata('userdata'),
];

Cant create a user using Laravel framework

I am using Laravel 4 and the following code suffers from a bug that i am not being able to find it :(
So i require your help.
One of the part of my code (that gives me the error) is shown here:
if($status == 'admin')
{
$role_id = 1;
}
else
{
$role_id = 2;
}
$check_role = DB::table('roles')->where('id', $role_id)->pluck('id');
if(($password == $repeat_password)&&($check_role != 0)&&($first_name != "")&&($last_name != ""))
{
$user = User::create(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));
return View::make('pages/manageUsers')->with('info', 'Success!');
}
else
{
return View::make('pages/manageUsers')->with('info','Failed!');
}
I want to make you sure that roles table exists and it hase two rows (id =1 is admin, and is=2 is user).
The following error is shown:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`leaves_db`.`users`, CONSTRAINT `users_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`)) (SQL: insert into `users` (`username`, `password`, `first_name`, `last_name`, `no_total_leaves`, `active`, `updated_at`, `created_at`) values (demo .demo, y$BuTWHRpfPl.OztGhTltjteqvGZZ6xcbzlAnCgwrZYRxRDxB.fuqHe, demo , demo, 0, 1, 2015-01-12 11:35:55, 2015-01-12 11:35:55))
As per above mentioned code, you are not inserting value of column role_id in table USERS.
Bare in mind that column role_id in table USERS is foreign key of column ID on table ROLES. So It should always be included in your every insert statement.
$user = User::create(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));
It seems the query that is running is not actually inserting the role_id. I cannot see it in the query that the error shows.
Thanks for your support. I needed to use this row instead:
DB::table('users')->insert(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));

Categories