Reputation: 135
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:
select
query to array, andpeople
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.
Upvotes: 1
Views: 1048
Reputation: 108
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..
Upvotes: 1
Reputation: 28564
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);
}
Upvotes: 0
Reputation: 21
I think that is right
$results = DB::table('user_master')->where('div_id', 1)->get();
Upvotes: 0