如何仅使用where子句获取搜索到的数据?

时间:2019-09-26 10:53:17

标签: php laravel laravel-5 eloquent

formData.append('grant_type', 'authorization_code');
      formData.append('code', code);
      formData.append('redirect_uri', redirect_uri);
      formData.append('client_id', client_id);

      const { data: authData } = await axios.post('https://eu.battle.net/oauth/token', 
        formData,
        {
          auth: {
            username: client_id,
            password: secret,
          },
          headers: {
            'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
          }  
        },
      )

我想显示category_id为$ id的数据。但是,每当我尝试搜索时,它就会向我显示数据库中的所有数据。假设我要搜索公里为24的数据。只有一个公里为24的数据。但是,除了显示一个数据之外,它还向我显示了数据库中的所有数据。

2 个答案:

答案 0 :(得分:1)

尝试类似的方法,根据选择的搜索参数(可选)添加条件

$query = PostAd::query();

if ( isset($id) ) {
    $query = $query->where('category_id',$id);
}

if ( isset($location) ) {
    $query = $query->where('district_id', 'LIKE', '%' . $location . '%');
}

if ( isset($condition) ) {
    $query = $query->where('condition', 'LIKE', '%' . $condition. '%');
}

$result = $query->get();

答案 1 :(得分:1)

您可以使用when方法有条件地将子句添加到查询中,具体取决于通过“真实性”测试的值:

PostAd::query()
    ->when($request->get('category_id'), function ($query, $categoryId) {
        $query->where('category_id', '=', $categoryId);
    })
    ->paginate();

作为第二个参数传递的闭包将收到两个参数:您可以修改的查询生成器实例,以及作为第一个参数传递给when方法的值。


您还可以更进一步,将过滤逻辑移至专用的类:

class PostAdFilters
{
    protected $request;
    protected $builder;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function apply(Builder $builder)
    {
        $this->builder = $builder;

        foreach ($this->request->query() as $key => $value) {
            // Convert something like `category_id` to `filterByCategoryId`
            $methodName = 'filterBy' . Str::studly($key);

            if (method_exists($this, $methodName)) {
                // If the method exists, call it
                call_user_func([$this, $methodName], $value);
            }
        }

        // Return the modified query builder
        return $this->builder;
    }

    private function filterByCategoryId($value)
    {
        $this->builder->where('category_id', '=', $value);
    }

    private function filterByKilometers($value)
    {
        $this->builder->where('kilometers', '=', $value);
    }

    // And so on...
}

class PostAd extends Model
{
    public function scopeFilters(Builder $query, PostAdFilters $filters)
    {
        return $filters->apply($query);
    }
}

然后您可以将此类插入控制器方法,并将其应用于模型:

public function search(PostAdFilters $filters)
{
    return PostAd::filter($filters)->paginate();
}

此方法基于https://laracasts.com/series/eloquent-techniques/episodes/4