2014-05-23 96 views
2

我來這裏請求一些關於這種情況的邏輯的幫助,如果可能的話,還有一些與代碼有關的幫助。Laravel多個插入到一個表中

所以,這是事情。假設我有這兩張桌子,當然有一對多的關係:

*These aren't the real tables, they're just to simplify things* 

**Table books** 
id 
name 

**Table books_reviews** 
id 
books_id 
user_id <-this would be the person who wrote a review 
details <-A varchar 140 field 
rating <-A 1 through 10 integer field 

現在好吧。我想要做的就是創建一個鏈接,它將只用一個表單向表中添加一行。是這樣的...

的HTML

<a href="#" id="myLink">Write one more review</a> 
<table id="mytable"> 

</table> 
<input type="submit"> <- This should sumbit all the rows for validation and insertion 

JavaScript的

$(document).ready(function(){ 
    var click=0; 
    $('#myLink').click(function(){ 
     click++; 
    $('#mytable').append('<tr> 
      <td><input type="text" class="form-control" id="details'+click+'" name="details'+click+'"</td> 
      <td><input type="text" class="form-control" id="rating'+click+'" name="rating'+click+'"</td> 
         </tr>'); 
    }); 
}); 

好了,我覺得這是很清楚的。當然,我也會在每一行添加特定的評論ID,但我認爲在這裏沒有必要這樣做。

事情是我不知道該怎麼做PHP明智。在我的控制器中寫什麼,以便它能夠檢測所有行併爲每行中的數據創建數組,然後驗證並插入它。 任何人都可以幫我一個忙嗎?

+0

所以,你有一個職位讀後感到控制器,並且要插入審查,以數據庫形式?你有沒有使用雄辯的ORM設置你的模型?他們的評論是否單獨提交?或有人可以繼續點擊「再寫一個評論」按鈕,然後在一個請求中提交多個評論? – Jeemusu

+0

書籍和評論的東西只是一個例子。我希望能夠多次點擊該鏈接,以便填寫相同模型的多種形式,並通過單擊提交按鈕將它們全部插入到表格中。 – arrigonfr

回答

4

如果你看一下你的JavaScript生成的源代碼,您應該看到您輸入的名稱會是這樣:

details1 rating1 
details2 rating2 
... 

這可能不是最好的選擇,我建議你的名字你所有的輸入如details[]rating[]。沒有必要使用櫃檯。

就像你可能知道,在laravel你應該使用輸入::所有()來獲取所有的表單數據。這個函數應該返回到你下面的數組:

# array: form data 
array(
    'details' => array(
     [0] => 'Content of details 1', 
     [2] => 'Content of details 2' 
    ), 
    'rating' => array(
     [0] => 'Content of rating 1', 
     [2] => 'Content of rating 2' 
    ) 
) 

要一次插入多行與laravel可以使用功能BookReview::insert($array),這個函數接收數組的數組在數據庫中添加。這個數組應該是這樣的一個:

# array: eloquent ready 
array(
    array(
     'details' => 'Content of details 1', 
     'rating' => 'Content of rating 1', 
    ), 
    array(
     'details' => 'Content of details 2', 
     'rating' => 'Content of rating 2', 
    ), 
) 

所以,你所要做的就是數組「表單數據」轉換爲陣「雄辯的準備」。這可以用一個簡單的算法來進行:

$input = Input::all(); 
$insert = array(); 
foreach($input['details'] as $key => $detail) { 
    $insert[$key]['details'] = $detail; 
} 
foreach($input['rating'] as $key => $rating) { 
    $insert[$key]['rating'] = $rating; 
} 
BookReview::insert($insert); 

PS:在我的例子中我沒有添加其他領域,如USER_ID和book_id。您應該將其添加到foreach中,將此信息添加到所有行中。

+0

太棒了!這正是我需要的。還沒有嘗試過,但我只知道它會通過閱讀你的代碼工作。還有一件事:使用ajax驗證每一行的最佳方法是什麼,這樣URL就不會重新加載,並告訴我錯誤在哪裏? – arrigonfr

+1

您可以在客戶端或服務器端進行驗證。在客戶端,您可以在輸入中使用'required'參數或使用javascript(我推薦Parsley庫)。在服務器端更復雜,因爲你必須驗證每個模型。爲了在服務器端做到這一點,我建議不要製作一個數組數組,建立一個BookReview對象數組,以便使用laravel的Validation類來逐個驗證它們。這將是很多工作,因爲你將不得不將錯誤發回到JavaScript並處理它們。 – LucasFerreira

+0

我現在看到了。謝謝,我現在就去解決 – arrigonfr