'UpdateorInsert method in dynamic column cominig from array

I have some misunderstanding with the UpdateOrInsert helper with the DB

    DB::table('table')
             ->updateOrInsert( );
            }  

I have a dynamic collection structured like this:

^ Illuminate\Support\Collection {#1534 ▼
  #items: array:9 [▼
    "it-IT" => array:1 [▶]
    "cs-CZ" => array:1 [▶]
    "de-DE" => array:1 [▶]
    "en-GB" => array:1 [▶]
    "en-US" => array:1 [▶]
    "es-ES" => array:1 [▶]
    "fr-FR" => array:1 [▶]
    "ko-KR" => array:1 [▶]
    "sk-SK" => array:1 [▶]
  ]

I would like to use the it-IT array as reference and Update the other languages or Insert a new line if the it-IT string don't exist.

This Collection comes from an array, I transform it in collectio just for use the chunk(); function.

The problem is, after a lot of tries, using in the correct way the UpdateOrInsert.

Cause, I undestand that I need to separe the reference with the rest, so I split the collection in two collection:

$coll = collect($array);
$chunks = $coll->chunk(500);
$refcol = collect($refArr);
$refchunks = $refcol->chunk(500);

foreach ($chunks as $chunk)
{
    DB::table('dictionaries')
        ->updateOrInsert($refchunks->toArray(),$chunk->toArray() );

} 

But this is not enought cause when it start to upgrade the data inside the database i get a strange query error:

select exists(select * from `dictionaries` where ((`1` = stringa di riferimento ))) as `exists`

so I think I have to split the collection in all languages collection, but the number and the languages are not always the same.

How can I do a foreach inside the UpdateOrInsert?

I have tried olso to using the Model way

Dictionary Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Dictionary extends Model
{
    protected $primaryKey = null;
    public $incrementing = false;
    public $timestamps = false;
}

But when I perform the save() but if the it-IT string already exist it go in exception.

I tell to my self "Never give up" so I tried a thing like this:

    try{
        Dictionary::save();
    } chatch (\Exception $e){
        Dictionary::update();
    }

But it save me the string like { 1: 'string in correct column'} and update method doesn't work.

Any way to help me?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source