php - 如何在 Laravel 4 中执行动态查询

标签 php mysql laravel laravel-4

我是 Laravel 新手。我正在尝试从选择列表构建查询。我收到以下错误

strtolower() 期望参数 1 为字符串

这是我的表格

        <form action="search" method="post" accept-charset="utf-8">
                <div class="form-group">

                    <select  name="temptype" class="form-control">
                        <option value="" selected="selected">Select Temp Type</option>
                        <option value="hygienist" >Hygienist</option>
                        <option value="dentist" >Dentist</option>
                        <option value="dentalassistant" >Dental Assistant</option>
                    </select>

                </div><!-- end username form group -->
        </div><!-- end .modal-body -->
        <div class="modal-footer">
            <input type="submit" name="submit"  class="btn btn-primary" />
        </div>
        </form>

这是我的路线

Route::post('search', function(){


    $temp = User::getTemps();

    return $temp;


});

这是我的用户模型中的方法...

 public static function getTemps()
    {

        $type = array (

            'hygienist' => Input::get('hygienist'),
            'dentist' => Input::get('dentist'),
            'dentalassistance' =>Input::get('dentalassistance')

        );


        $temps = DB::table('users')
            ->select('usertype', $type) <---- I think this has to be a string but my question is how do I make this dynamic... How do I pass the string value from what the user selects and pass it into the query?>
            ->get();

        return $temps;
    }

最佳答案

您的表格绝不会发布卫生员牙医 dentry 援助。因此 Input::get('hygienist') 将为 null。该表单将使用从选择列表中选择的来发布temptype。也就是说,如果我转到该表单,选择Hygienist并单击提交,您将得到Input::get('temptype') = "Hygienist"

因此您应该将 getTemps 更改为:

public static function getTemps()
{
    // Create a array of allowed types.
    $types = array('hygienist', 'dentist', 'dentalassistance');

    // Get what type the user selected.
    $type = Input::get('temptype');

    // Make sure it is a valid type.
    if(!in_array($type, $types))
    {
        return App::abort(500, "Invaild temptype.");
    }



    $temps = DB::table('users')
        ->select('usertype', $type)
        ->get();

    return $temps;
}

关于php - 如何在 Laravel 4 中执行动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19173903/

相关文章:

mysql - 如何在一个mysql docker容器中启动多个实例

php - Nginx Laravel 4 url​​ 查询重写

php 使用 mysql 插入、查找、更新

php,realpath 与 realpath + file_exists 用法

php - Contenteditable 与输入替换

来自 linux 命令行的 mysql 数据库,数据库名称中带有点

javascript - Node JS 中的多重查询

php - 在 laravel 的测试套件中只运行一个单元测试

email - 值未定义

php - 为 Controller 创建文件夹后找不到模型