2016-11-18 45 views
1

请帮助我。我想问:Laravel查询和阵列

假设我有2个表格:user_masterpeople

现在我正在使用Laravel 5.1框架在PHP中构建一个应用程序,从user_master表中选择数据(在where子句中有一些约束)并插入到people表中。

的代码是:

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. 
    } 
} 

我的问题是:

  1. 如何保存select查询到阵列的结果,并
  2. 使用插入数组到people表RAW查询(INSERT INTO people VALUES (...))。

P.S.:我的查询是RAW查询,不是使用雄辩。请提供没有雄辩的答案。

非常感谢你的回答。

+0

任何使用RAW查询的具体原因。 1)需要使用' - > get();'方法在你的'$ result'变量中得到结果 –

+0

你可以使用array_push()来创建一个foreach循环的数组 – lewis4u

+0

@ lewis4u:你能给我举个例子吗? ? – joshua14

回答

1

我也做了同样的情景是这样

$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, 
        ) 
      ); 
     } 

改变你喜欢按照你的逻辑,它的作品100%完美..

+0

这是我正在寻找的答案。非常感谢 :) – joshua14

0

如果您的表和主表具有相同的结构,您只需在下面的代码中设置主键。如果他们不在同一个结构中,则必须将结果调整为人员结构,然后插入到人员表中。

希望它会有所帮助。

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); 
    } 
0

我认为这是正确的

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