使用Eloquent Builder连接查询


Concatenate queries using Eloquent Builder

如何使用Eloquent Builder连接查询?

我正在基于条件(where子句)构建查询,并从URL获取限制和偏移量。然后将这些查询传递给->get()方法以获取结果。我想使用Eloquent而不是Query构建器来完成它。

这就是您在雄辩中构建查询的方式(我给出了一个使用多个where子句的例子):

$result = ModelName::where('key_1', '=' , 'value_1')
                     ->where('key_2', '>', 'value_2')
                     ->take(4)
                     ->offset(2)
                     ->get()

take()方法将结果的数量限制为4,偏移量为2。

http://laravel.com/docs/5.0/eloquent


更新

根据OP的问题https://laracasts.com/discuss/channels/general-discussion/eloquent-query-builder,我正在更新我的答案。

你可以这样做:

if($params)
{
    $query = $this->model;
    foreach($params['search'] as $param)
    {
        $query = $query->where($param['where'],'=',$param['value']);
    }
    if (isset($params['start']))
    {
        $query = $query->offset($params['start'] );
    }
    if(isset($params['count']))
    {
        $query = $query->take($params['count']);
    }
    if (isset($params['sortColumn']))
    {
        $ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
        $query = $query->orderBy($params['sortColumn'], $ascending);
    }
}
$query->get();

您需要的是将函数的结果再次分配给模型。

你有:

if($params)
    {
        foreach($params['search'] as $param)
        {
            $this->model->where($param['where'],'=',$param['value']);
        }
        if (isset($params['start']))
        {
            $this->model->offset($params['start'] );
        }
        if(isset($params['count']))
        {
            $this->model->take($params['count']);
        }
        if (isset($params['sortColumn']))
        {
            $ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
            $this->model->orderBy($params['sortColumn'], $ascending);
        }
    }
$this->model->get();

你需要使用:

if($params)
    {
        foreach($params['search'] as $param)
        {
            $this->model = $this->model->where($param['where'],'=',$param['value']);
        }
        if (isset($params['start']))
        {
            $this->model = $this->model->offset($params['start'] );
        }
        if(isset($params['count']))
        {
            $this->model = $this->model->take($params['count']);
        }
        if (isset($params['sortColumn']))
        {
            $ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
            $this->model = $this->model->orderBy($params['sortColumn'], $ascending);
        }
    }
$data = $this->model->get();