使用query Builder构建动态laravel DB查询


Building a dynamic laravel DB query using Query Builder

我有一个在Laravel框架上运行的跟踪系统。跟踪系统允许用户使用JSON格式的结构从网站输入他们的跟踪查询,然后传递到服务器进行处理。然后,服务器将根据输入中给出的JSON结构从数据库中查询所有相关数据。当前的代码结构有点多余,如下所示:

if($a == true)
{
    $data = DB::table('table')
    ->select('item1')
    ->where('item2', '=', $a)
    ->get();
    if($limit !== null)
    {
        $data = DB::table('table')
        ->select('item1')
        ->where('item2', '=', $a)
        ->take($limit)
        ->get();            
    }       
}
/*the code goes on and on*/

注意,在上面的示例代码中,有什么方法可以减少代码的冗余部分吗?比如,在我的脑海里,就像这样:

public function process()
{
    $data = DB::table('table')
    ->select('item1')
    $a == true ? "->where('item2', '=', $a)" : '';
    $limit !== null ? "->take($limit)" : '';
    ->get();
}

所以你可以看到,缩短的代码和长代码做的是完全一样的事情。我知道我的想法在实际场景中是不可用的,但是否有任何类似的方法可以像我想的那样工作?

Thanks in advance

构建器构建查询,但是直到运行get方法才获取数据。试一试:

if($a == true)
{
    $query = DB::table('table')
    ->select('item1')
    ->where('item2', '=', $a);
    if($limit !== null)
    {
         $query->limit($limit);   
    }
    $data = $query->get();
}

limittake相同。这只是个别名

我通常做的是

$query = 'DB::table('table');
$query->select('item1');   //i prefer $query->select('DB::raw('table.item1 AS item1'));
if($a)
{
    $query->where('item2', '=', $a);
}
if($limit)
{
    $query->take($limit);
}
$data = $query->get();

通过这种方式,您可以根据您想要添加的查询的附加过滤器进行调整。