douba4933
douba4933
2014-02-21 15:50
浏览 442
已采纳

Laravel查询“if”条件?

I'm trying to make an advanced search form with Laravel 4, and this is the query:

$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;

The problem is that the user might not use all the input fields. So i want to include some if conditions in this part:

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

.. so if the input is empty, to remove the "where" condition.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyi1748
    dongyi1748 2014-02-21 15:56
    已采纳
    $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);
        }
    });
    

    Newer version of Laravel have a when method that makes this much easier:

    ->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);
            });
        }
    });
    
    点赞 评论
  • dongwo2772
    dongwo2772 2014-02-21 15:55

    You could wrap each where in an if statement.

    $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;
    

    Something along those lines would work I believe.

    点赞 评论

相关推荐