mardi 3 octobre 2017

Laravel bulk insert with column that contains an array

I have a data structure that has the following columns:

id => increments()
name => string()
data => string()

In my model, I cast the data column to an array.

    protected $casts = [
    'data' => 'array'
    ];

In a for loop I create a multidimensional array like this called $data and I assign it to the 'data key of my $temp array and I push it in an array called $finals.

$temp = [
'name' => $variable1,
'data' => $data
]

array_push($finals, $temp)

Unfortunately, Laravel's bulk insert does not allow me to execute a bulk insert when I have a multidimensional array where one of the values is an array. In order to insert this type of multidimensional array I have to create the following foreach loop (which I don't like)

foreach($finals, $final)
{
    ModalName::create($final);
}

Is there a way that I could insert such a data structure in a single statement and not loop through each element of the array. Something like

ModelName::create($finals);

Note that, I've tried to replace the value of the 'data' key with a hardcoded static value in place of the array and the rows are inserted correctly.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire