lavina's avatar

Raw input into DB

Hello,

I've been attempting to mass insert rows into a table, and update if it already exists. This functionality is not supported by laravel(only for single row inserts as far as i've found), thus i am trying to write a raw insert, but it seems i am using the wrong sql sintax:

DB::insert('INSERT INTO
        products (name, description, created_at, updated_at)
        VALUES
        (\'name\',\'desc\',\'2020-02-19 09:03:45\',\'2020-02-19 09:03:45\'),
    (\'name\',\'desc\',\'2020-02-19 09:03:46\',\'2020-02-19 09:03:46\')
        ON DUPLICATE KEY UPDATE updated_at=\'2020-02-19 09:03:47\';
        ');

And duplicate key seems to only work on primary keys, which i let the table generate, thus each input is unique, how can i specify a different column to check duplicates for?

0 likes
5 replies
a4ashraf's avatar

Hi @lavina

Try this one, its work for you, replace your fields with Data object

App\Product::createMany([
        [
            'name' => $data->your_name,
            'description' => $data->description,
            'created_at' => $data->created_at,
            'updated_at' => $data->updated_at,
        ],
        [
            'name' => $data->your_name,
            'description' => $data->description,
            'created_at' => $data->created_at,
            'updated_at' => $data->updated_at,
        ]
    ]);

Snapey's avatar

I feel I should apologise for people that don't read the question.....

Xsecrets's avatar

DB::insert does not accept raw sql queries try

 DB::statement('your query here'); 
jlrdw's avatar

You have to set yourself up some strategic if statements and workout that logic to either update or create.

Maybe work with laravels update or create method (browse the docs). It might work.

Many of these types of questions are just logic problems to be worked out.

You have to figure out which field to use as a comparator.

Please or to participate in this conversation.