1

please help me. I want to ask:

Let say I have 2 tables: user_master and people.

Now I am currently build an application in PHP with Laravel 5.1 framework that select the data from user_master table (with some constraint in where clause) and insert into people table.

The code is :

public function handle() {
   $results = DB::select(DB::raw("SELECT * FROM user_master WHERE div_id = 1"));

   foreach ($results as $res) {
        //saving to array
        //insert query to table people here.
    }
}

My questions are:

  1. How to save the result of select query to array, and
  2. Insert that array into people table using RAW query (INSERT INTO people VALUES (...)).

P.S.: My query is RAW query, not using Eloquent. And please provide answer without Eloquent.

Thank you so much for any answer.

3
  • Any specific reasons behind using RAW queries. 1) Need to use ->get(); method to get result within your $result variables Commented Nov 18, 2016 at 8:11
  • you can use array_push() to make an array of your foreach loop Commented Nov 18, 2016 at 8:23
  • @lewis4u: can you give me some example?? Commented Nov 18, 2016 at 8:26

3 Answers 3

1

I have done the same scenario like this

$users=DB::table('Users')->where('created_at' ,'>=','2016-09-06')->get();
        foreach ($users as $user){
            DB::table('users_report')->insert(
                array(
                    'id' => $user->id,
                    'username' => $user->username,
                    'lastname' => $user->lastname,
                    'email' => $user->email,
                    'created_at' => $user->created_at,
                    'updated_at' => $user->updated_at,
                    )
            );
        }

change your like according to your logic , its works 100% perfectly..

Sign up to request clarification or add additional context in comments.

1 Comment

this is the answer I'm looking for. Thank you so much :)
0

I think that is right

$results = DB::table('user_master')->where('div_id', 1)->get();

Comments

0

if your table and master have the same strucure, you just set the primary key in the below code. If they are not in the same structure, you have to ajust the results to the structure of the people bfore you insert to peopel table.

hope it will helps.

function delete_col(&$array, $offset) {
    return array_walk($array, function (&$v) use ($offset) {
        unset($v[$offset]);
    });
}
   public function handle() {
$results = DB::table('user_master')->where('div_id', 1)->get();
delete_col($results, $premiarykeyOfuser_master);

    DB::table('people')->insert($results);
    }

Comments

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.