PhP中的简单数据库查询代码问题

时间:2016-03-23 23:53:10

标签: php mysql

我是PhP的新手。我从其他团队成员那里得到了一个代码,只是想做一个小改动。

代码是从DB获取项目列表。它使用“where”子句将行业参数与sql查询中的行业输入参数进行比较。这段代码工作正常。我只想用query-> where子句替换“=”和“LIKE”比较。

这是当前带有“=”的代码

 public function feed($industry=null){
    $query = DB::table('startups as s')
    ->leftjoin('founders as fd','fd.startup_id','=','s.id');
    if($industry)
        $query->where('s.industry','=',$industry);      
    $result = $query->select('s.id as sid','fd.name as fdname','fd.email','fd.contact','s.*','s.created_at',DB::raw("(select sum(f.fund_amount) from funds as f where f.startup_id=s.id and f.fund_amount>0)as 'total'"))
    ->groupBy('s.id')
    ->get();
    return json_encode($result);        
},

下面是我用LIKE替换“=”的多次尝试之一(但到目前为止还没有选项有效 - 看起来很简单,但再次没有在PhP中工作,所以我错过了一些东西)

 public function feed($industry=null){
    $industryFilter = "%{$industry}%";
    $query = DB::table('startups as s')
    ->leftjoin('founders as fd','fd.startup_id','=','s.id');
    if($industry)
        $query->where('s.industry','LIKE',$industryFilter);     
    $result = $query->select('s.id as sid','fd.name as fdname','fd.email','fd.contact','s.*','s.created_at',DB::raw("(select sum(f.fund_amount) from funds as f where f.startup_id=s.id and f.fund_amount>0)as 'total'"))
    ->groupBy('s.id')
    ->get();
    return json_encode($result);        
},

1 个答案:

答案 0 :(得分:0)

看起来你已经正确地修改了where子句,但试试这个:

public function feed($industry=null){

    $query = DB::table('startups as s')
        ->leftjoin('founders as fd','fd.startup_id','=','s.id');
    if( $industry ){
        $query->where('s.industry','LIKE', '%'.$industry.'%');     
    }

    $result = $query->select('s.id as sid','fd.name as fdname','fd.email','fd.contact','s.*','s.created_at',DB::raw("(select sum(f.fund_amount) from funds as f where f.startup_id=s.id and f.fund_amount > 0)as 'total'"))
        ->groupBy('s.id')
        ->get();

    return json_encode($result);        
}

希望这有效并且有所帮助