2016-11-18 43 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();