0

I'm inserting a group of elements in database, I'm trying to get one element for each row but I'm obtaining all elements in one row and every row from the database is repeated like this

enter image description here

I would like to get one element for row in the column.. I'm using this query

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif')
   ->distinct()
   ->get();

    foreach ($data as $val) { 
    DB::table('clientes_view')->insert(['resultado' => $data]);

How could I fix it?

1 Answer 1

2

Because you are inserting the $data instead of $val,

You can get all $data, and insert them at once, like this:

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif AS resultado')
   ->distinct()
   ->get();
// If you are using Eloquent, you can just use ->toarray();
// For query builder, you need to change stdClass to array, so I use json_decode()
$data = json_decode(json_encode($data, true), true);

DB::table('clientes_view')->insert($data);

updateOrInsert only supports one record, so if you want to use this method:

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif AS resultado')
   ->distinct()
   ->get();
$data = json_decode(json_encode($data, true), true);
forEach($data as $val) {
    DB::table('clientes_view')->updateOrInsert($val, $val);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Im getting this error Object of class stdClass could not be converted to string
I think that I have to invoke the class because I got this error Call to undefined function App\Http\Controllers\ATC\json_ecode() Which class do I have to invoke?
@LaravelOscar sorry, that's my mistake, It's json_encode()...
@LaravelOscar u'r welcome, updateOrInsert only support to one record, if you want to use this method, you need to loop it, like foreach ($data as $val) { Model::updateOrInsert($val, $val)
@LaravelOscar I have post it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.