【问题标题】:Laravel query with "if" conditions?带有“if”条件的 Laravel 查询?
【发布时间】:2014-03-23 05:37:43
【问题描述】:

我正在尝试使用 Laravel 4 制作高级搜索表单,这是查询:

$result = DB::table('users_ads')
        ->join('ads', 'users_ads.ad_id', '=', 'ads.id')         
        ->orderBy($column, $method)
        ->where('status', TRUE)
        ->where(function($query) use ($input)
        {
            $query->where('short_description', $input['search'])
                    ->where('category', $input['category'])
                    ->where('product', $input['product']);

        })
        ->join('users', 'users_ads.user_id', '=', 'users.id')
        ->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
        ->get();

    return $result;

问题是用户可能不会使用所有输入字段。所以我想在这部分包含一些 if 条件:

$query->where('short_description', $input['search'])
                    ->where('category', $input['category'])
                    ->where('product', $input['product']);

.. 所以如果输入为空,就去掉“where”条件。

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    您可以将每个 where 包装在 if 语句中。

    $query = DB::table('user_ads')
                ->join('ads', 'users_ads.ad_id', '=', 'ads.id')
                ->orderBy($column, $method);
    
    if ($input['search']) {
        $query->where('short_description', $input['search']);
    }
    
    if ($input['category']) {
        $query->where('category', $input['category']);
    }
    
    $query->join('users', 'users_ads.user_id', '=', 'users.id')
        ->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
    
    $result= $query->get();
    
    return $result;
    

    我相信这些方法会奏效。

    【讨论】:

    • 并不是说它有很大的不同,但你已经把术语颠倒了。在get 调用之前是查询,之后是结果。
    • 哦,哈哈!我只是使用操作提供的变量,并没有真正考虑过。我会修改它!
    • OP 将所有内容链接到get 调用,所以它确实是一个结果。
    • 是的,没错。我没有看那么多变量名。不管怎样,我更喜欢你的回答。我相信这是一种更简单、更清洁的方法。
    • 如果你得到一个纯白的屏幕,那会很好。你有没有告诉应用程序输出一个视图或任何东西?如果没有输出,那么您将看到的只是一个白屏。
    【解决方案2】:
    $filters = [
        'short_description' => 'search',
        'category' => 'category',
        'product' => 'product',
    ];
    
    .....
    
    ->where(function($query) use ($input, $filters)
    {
        foreach ( $filters as $column => $key )
        {
            $value = array_get($input, $key);
    
            if ( ! is_null($value)) $query->where($column, $value);
        }
    });
    

    较新版本的 Laravel 有一个 when 方法,让这变得更容易:

    ->where(function ($query) use ($input, $filters) {
        foreach ($filters as $column => $key) {
            $query->when(array_get($input, $key), function ($query, $value) use ($column) {
                $query->where($column, $value);
            });
        }
    });
    

    【讨论】:

    • +1 为此,效果会很好,而且比我的回答要好。
    猜你喜欢
    • 2016-11-06
    • 2021-07-25
    • 2020-10-24
    • 2017-01-06
    • 2012-02-02
    • 2019-02-08
    • 2018-01-14
    • 2017-03-30
    • 2020-08-15
    相关资源
    最近更新 更多