1

I am new to PhP. I got a code from some other team member and just trying to make a minor change.

The code is to get a list of items from DB. It uses "where" clause to compare industry parameter with the industry input parameter in sql query. This code works fine. I just want to replace "=" with "LIKE" comparison for the query->where clause.

Here is the current code with "=" which works

 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);        
},

Below is one of my multiple attempts to replace "=" with LIKE (but so far no option has worked - seem simple but again haven't worked in PhP so I am missing something)

 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 Answers1

0

It looks like you've amended the where clause correctly but just try this:

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);        
}

Hopefully that works and helps