$wpdb->insert() throws "foreign key constraint fails" error - php

I have the following code:
$chck = $wpdb->insert( 'poruke_viber', array(
'id' => $data['message_token'],
'tekst' => $messageText,
'primljena' => '1',
'user_id' => $user['id'],
'vrijeme_epoch' => $data['timestamp']
));
logData($wpdb->last_error);
and it throws error:
Cannot add or update a child row: a foreign key constraint fails
It bugged me for couple of hours, I checked that I already have user_id in my parent table, and everything.
Until I tried replacing insert with query.
So when I did:
$wpdb->query('INSERT INTO poruke_viber (id, tekst, primljena, user_id, vrijeme_epoch)
VALUES ("'.$data['message_token'].'","'.$messageText.'","1","'.$user['id'].'","'.$data['timestamp'].'")');
It worked like a charm!
I'm here with the working code but not understanding what happened.
Is it wrong to use $wpdb->insert() on a table that has a foreign key?

Related

Laravel inserting by relationship to composite key table

I have these tables currently:
User table
id (primary key), name, email
User Model
protected $fillable = ['name', 'email'];
protected $visible = ['id','name','email'];
//Relationship
public function customAttributes()
{
return $this->hasMany('App\Models\UserAttribute');
}
UserAttribute Table
user_id, attribute_id, value //user_id and attribute_id is a composite key, both foreignkeys acting as primary keys establishing an unique combination
UserAttribute Model
protected $fillable = ['user_id', 'attribute_id','value'];
protected $visible = ['user_id', 'attribute_id','value'];
I'll use the following example to explain the issue:
$user = $this->user->create(['name' => 'admin', 'email' => 'admin#admin.com']);
//This works
$user->customAttributes()->save(new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']));
//This does not work
$user->customAttributes()->create([new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1'])]);
I could just repeat the save for every custom that I want since it works, but I'm trying to figure out why create doesn't work.
The error I'm getting when I use create is (and yes, I've checked the record exists in the table that isn't listed here):
Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`user_attributes`,
CONSTRAINT `user_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`))
This is the query it's trying to execute:
insert into `user_attributes` (`user_id`) values (1)
I'm just curious at why this doesn't work with create, I'm not sure if it's something related to this specific scenario (create to a composite key table by relationship). It's somewhat ignoring the value and attribute_id field in the query that is executing
try this:
$user->customAttributes()->create(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']);
customAttributes() already returns you instance of UserAttribute model, you don't need to enject that dependency when you use create() method via that relation
your query should be like below;
$user->customAttributes()->insert([
[
'user_id' => $user->id,
'attribute_id' => 1,
'value' => 'Just a custom1'
],
[
'user_id' => $user->id,
'attribute_id' => 2,
'value' => 'Just a custom2'
],
]);

Inserting with relationships in laravel

I am facing a problem in Laravel 5.3 that I looked the docs and also searched web but didn't find anything on it.
I am using Laravel Relationships to join two tables. Now I want the data to be inserted on both the tables at the same time after the user submits a form. The catch in this is the first table is the primary one say "users" and second one "xyz" belongsTo the first table. The table "xyz" contains "users_id" column that connects both the tables. And obviously "users_id" is the "id" column of "users" table.
Now the problem arriving is that I want to insert the data in "users" table (that is easily done) and "xyz" table at the same time. The User::create() function will create the user data easily and it is working also but for inserting the data in "xyz" table I will be needing the "user_id" column data and ID will not be generated until the user is created as ID column has Auto-Increment attribute activated.
Code:
$user = new User;
$inputArry = array('data1' => $request['field1'],
'data2' => $request['field2'],
'data3' => $request['field3'],
);
$user->create($inputArry);
$user->xyz()->create([
'user_id' => $user->id,
'name' => $request['name'],
'about' => $request['desc'],
'tag' => $request['tag'],
]);
Above is the code that I am using for this purpose but it is giving me a error.
Error:
QueryException in Connection.php line 761:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'soft_id' cannot be null (SQL: insert into `xyz` (`user_id`, `name`, `about`, `tag`, `updated_at`, `created_at`) values (, John, I am John, dev, 2016-11-09 21:01:29, 2016-11-09 21:01:29))
One way of inserting related table is using relations as:
$user = User::create($user_inputs);
$xyz = $user->xyz()->create($xyz_inputs);
It will automatically fills the user_id in the xyz table.
If you need insert many items, use createMany or saveMany method.
For example:
$post = App\Post::find(1);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
In the offical laravel docs:
https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models
You can create them like this instead of saving them on same time...
$id = User::create($input_arr)->id;
Xyz::create([
'user_id' => $id,
...
]);

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));

Add foreign key in Yii migrations

I try to add foreign key to table, but when I run migration I getting this error:
General error: 1005 Can't create table 'chooseone.#sql-49a_49'
Its strange because chooseone is the name of my database. Here is how I try to add FK:
$this->addForeignKey('FK_user_profile', 'tbl_profile', 'user_id', 'tbl_user', 'id', 'CASCADE', 'CASCADE');
So what I am doing wrong?
I solve this issue. I change my definition of id column in tbl_user:
'id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
to
'id' => 'pk',
and all works properly.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

I am using cakePHP framework in my web project,It seems many people have already ask similar question before.Even I try for those I couldn't find the answer.
Here is the error I got'
Database Error
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`fit_or_fat`.`disease_suggestions`, CONSTRAINT `disease_suggestions_ibfk_1` FOREIGN KEY (`disease_id`) REFERENCES `diseases` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Query: INSERT INTO `fit_or_fat`.`disease_suggestions` (`title`, `suggestion`, `disease_id`, `modified`, `created`) VALUES ('cholestorol', 'dddddddddddddddd', 'dd', '2014-08-24 00:04:32', '2014-08-24 00:04:32')
This is my model
'disease_id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'disease_id must not be empty',
),
'custom' => array(
'rule' => '/[\w\s\d., \-_]+/',
'message' => 'user_id can only contain simple and capital letters, 0-9 numbers, . , - _ space and tabs only.',
),
),
You appear to be adding dd to the disease_id column. Which has a constraint. Most often ID columns are numerical. So this warning is telling you the the query is wrong, or specifically trying to insert values not allowed.
INSERT INTO `fit_or_fat`.`disease_suggestions` (`title`, `suggestion`, `disease_id`, `modified`, `created`) VALUES ('cholestorol', 'dddddddddddddddd', 1, '2014-08-24 00:04:32', '2014-08-24 00:04:32')
Will most likely be allowed (I have no idea what disease is on ID 1 but that's another issue all together).

Categories