2016-03-07 86 views
0

在我的用戶註冊工作流程中,我要求用戶選擇一個預定義的分類列表(我使用了一系列複選框)。目前,當我們移動到下一步時,我會使用這些值更新我的模型(如果未選中此框,則爲空白值)。這些目前不是作爲一個數組來構造的,而是作爲一個獨立的不同的複選框。Laravel搜索值列表

我的2個問題如下:

1)我看了,如果我保存複選框作爲數組我將無法輕鬆地在數據庫中搜索用戶與特定分類。 2)如果這是真的,我很好,我目前的結構,但我需要正確驗證(服務器端),至少有一個複選框被選中,否則提供一個錯誤。我已經嘗試了以下內容,但它不返回任何內容,並且數據庫記錄在每列中都沒有任何內容。

if ($request->all() === "") 
{ 
    return Request::json('you must select one'); 
} 

數據庫表遷移:

Schema::create('user_type', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('user_id'); 
    $table->string('games'); 
    $table->string('art'); 
    $table->string('music'); 
    $table->string('building_stuff'); 
    $table->string('educational'); 
    $table->timestamps(); 
}); 

的Javascript:(我提交的AJAX)

$('.modal-type-btn').click(function(e){ 
    e.preventDefault(); 

    if($('.checkbox-games').is(':checked')) 
    { 
     var games = "games"; 
    } else { 
     var games = ""; 
    } 

    if($('.checkbox-art').is(':checked')) 
    { 
     var art = "art"; 
    } else { 
     var art = ""; 
    } 

    if($('.checkbox-music').is(':checked')) 
    { 
     var music = music; 
    } else { 
     var music = ""; 
    } 

    if($('.checkbox-building-stuff').is(':checked')) 
    { 
     var buildingStuff = "buildingstuff"; 
    } else { 
     var buildingStuff = ""; 
    } 

    if($('.checkbox-educational').is(':checked')) 
    { 
     var educational = "educational"; 
    } else { 
     var educational = ""; 
    }  

    $.ajax({ 
     type: "POST", 
     url: "/profile/setup/1", 
     data: {games:games, art:art, music:music, buildingStuff:buildingStuff, educational:educational}, 
     error: function(data){ 
      console.log(data); 
     }, 
     success: function(data){ 
      console.log(data); 

     } 
    }); 

謝謝!

回答

0

所以,首先你多使用它們作爲一個數組,做類似的更好:

HTML:

<input type="checkbox" name="options[games]" value="1" /> 

這種方式,你可以得到表單數據並傳遞到您的通話$.ajax

... 
data: $('form').serialize(), 
.... 

,然後在你的控制器,檢查的options的長度至少一個:

$options = Input::get('options'); 
if(count($options) > 0){ ... } 

你也可能會想定義的「允許」選項的列表,然後用它來構建查詢:

private $_allowed_options = array('education', 'buildingStuff' ...); 

public function update() 
{ 
    $options = Input::get('options'); 
    foreach($this->_allowed_options as $allowed_options){ 
    if(array_key_exists($allowed_option, $option)){ 
     // add this option to our sql to add it to our user 
     // as they have selected it 
    }else{ 
     // the user didn't select this one, so add it to be removed 
     // from the users 
    } 
    } 
} 
+0

感謝。所以,有人評論說,如果以數組形式存儲,搜索更加困難聽起來不正確。 –

+0

如果你使用Eloquent和多對多關係,你應該只能使用'sync',只有允許刪除的項目。除非你告訴它不使用第二個參數[見:BelongsToMany.php](https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php#L737) – ash