logo
down
shadow

Lumen: Foreign key constraint violation when inserting data one to many


Lumen: Foreign key constraint violation when inserting data one to many

By : Mostafa Fayed
Date : November 19 2020, 03:01 PM
hope this fix your issue You need to specify a foreign key. For example, if you have User has many Articles relationship and you're trying to insert a new Article, you need to do this:
code :
$user->articles()->create($request->all()); // Foreign key will be inserted automatically.
$this->article->create(array_merge(['user_id' => auth()->id()], $request->all()));


Share : facebook icon twitter icon
Laravel - inserting foreign keys causes Integrity constraint violation

Laravel - inserting foreign keys causes Integrity constraint violation


By : Apurva Bhasale
Date : March 29 2020, 07:55 AM
hope this fix your issue I have two related models Domainand Server. I'm trying to insert data to my tables using a form. here is my store function : , Have you tried?
code :
  $new_domain = $domain->create($request->all());

  $server->domain()->associate($new_domain);
  $server->save();
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails


By : Zweli Tgul Mmualefe
Date : March 29 2020, 07:55 AM
may help you . I have users and projects table. in project table user_id is foreign key. i create a project and when i try to save the project details its showing this ERROR: , You have two alternatives :
code :
$data = $request->all();
$data['user_id'] = Auth::user()->id;
Project::create($data);
//....
Auth::user()->project()->create($request->all());
insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048


By : West Hollywood Mover
Date : March 29 2020, 07:55 AM
it fixes the issue It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:
code :
<?php


// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();


try {

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
    // You do not need to return response from here
    // echo json_encode($data); 
    // var_dump($data);


    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)    
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";


    $stmt    = $pdo->prepare($sql);

    // the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
    // notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
    // so, I just added some dummy data.
    $p_fname = 'Patient first name';
    $p_lname = 'Patient last name';
    $p_gender = 'm';
    $p_condition = 'condition';
    $p_birthdate = '1999-01-01';
    $p_emergencycontact = 'Contact';

    $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
    $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
    $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
    $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
    $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
    $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);

    // You do not have any $acc_id variable in your code. To get data from your fetch you need to do 
    // like this:
    $stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR); 


    $stmt->execute();

    header('Access-Control-Allow-Origin: *');

    // If you want to get the acc_id in your client side through the AJAX call, combine both
    // mesage and data in the same JSON object.
    echo json_encode(
        array(
            'message' => 'Congratulations the record was added to the database'
            'data' => $data
        )
   ); 
} catch(PDOException $e) {
    // make sure to send the proper status code
    http_response_code(500);
    // even error should be sent back as in json so that your javascript client can
    // easily parse it
    echo json_encode(
        array(
            'error' => $e->getMessage()
        )
    );
}
?>
integrity constraint violation: unique constraint or index violation on Foreign key HSQL

integrity constraint violation: unique constraint or index violation on Foreign key HSQL


By : Supriya
Date : March 29 2020, 07:55 AM
seems to work fine I'm testing the underlying model of a HSQL database using Hibernate/Spring Boot and I've run into an issue I cannot find a solution to. , The issue is
@ManyToOne(cascade = CascadeType.ALL)
JPA delete fails (integrity constraint violation: foreign key no action) - data model too convoluted?

JPA delete fails (integrity constraint violation: foreign key no action) - data model too convoluted?


By : J. Ossama
Date : March 29 2020, 07:55 AM
hop of those help? Here you are trying to delete the parent without deleting the child which have foreign key referencing to the parent.
Here, before you delete p you have to delete children for p. You can get that by : p.getClazzes();
Related Posts Related Posts :
  • How to add new Custom Title in Woocommerce My Account sidebar?
  • Mattermost, slash command response as message attachment
  • Library failure when installing Libsodium (Amazon EC2)
  • Page footer centering using MPDF
  • HTML : Different link at each click
  • TCPDF how to prevent page break within a block (split content)?
  • How to insert values in table
  • Php query builder for OR and AND condition
  • ZF2 Ajax call returns all information instead of just the id being sent
  • Order custom post types in WordPress by the meta_value of another plugin
  • saving bank row using array
  • Convert URL with query parameters to guzzle
  • Get POST values by index in codeigniter
  • Composer is not functioning?
  • Retrieving an Array with Axios in Laravel
  • How to get the last child of each cd element?
  • How to allow users to connect their own domain
  • PHP multidimensionnal array and empty value
  • PHP if statement doesn't work properly (paradoxical)
  • BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::searchable()
  • PHP explode() returns array inside an array
  • Echo parse error for creating new php file
  • PHP Parse error: syntax error, unexpected '?'
  • PHP Session not working correctly on a particular host
  • laravel how to get the extremities tables through the pivot
  • Show duplicate value in array only one but show all others
  • SMTP Emails not send (There is something wrong with server config as code is fine for other servers)
  • I can't turn off debug bar in Laravel on production
  • PHP creating multidimensional json
  • Increment value with get
  • Laravel 5.5: Convert query builder to eloquent
  • Reverse proxy onto a WordPress page?
  • Jumble Solver url rewrite
  • Using .htaccess to Execute php if directory of the same name not found
  • mysql - Unknown Column In Where Clause
  • Receive Emails into my Admin panel with php or other
  • PHP - adding only distinct value to an array in foreach loop not working
  • How to pass date picker from one page to another
  • Try catch always return error when I insert 2 data
  • Php redirect not working on submission
  • How to get array value from wordpress database get_results
  • how Automatically go from first.php to second.php
  • uploading file not working in codeigniter 3 error: you did not select any file
  • Yii2, gridview can not show some html tags inside cells
  • What are the thing we need to configure to implement live notification module (using redis and socket.io) in https serve
  • How to handle multi criterias search in PHP
  • PHP - Get maximum key and its value in array
  • PHP: how to retrieve all the metrics and dimensions from the Google Metadata API?
  • Deliver php mails to special-character-email adresses, such as äüö
  • Delete a single row from an MSSQL table from PHP
  • Property [name] does not exist on this collection instance
  • Pass input value through PHP parameter
  • Running two PHP versions on the same server (STRETCH)
  • Checking if a file has been selected for upload
  • Model not updating laravel
  • How to add a description of words from text to an array, to an array key by passing words?
  • Nginx rewrite rule not not passing variables if "/" is at the end of the url
  • Modify decimal point and thousands separator without changing the number of decimals
  • Remove PHP errors from CLI and PHPMyAdmin
  • Yii2 rest api - Url manager add parameters
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org