2016-03-07 110 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