如何在laravel 5的雄辩数据库中添加子查询?

时间:2017-02-03 13:05:14

标签: laravel eloquent laravel-5.3

如果我使用/api/location/event_name/event_status,我正在使用eloquent在laravel 5.3中构建一个api,然后我就会得到结果。

但是当我使用/api/location/event_name/api/location/时,没有任何事情发生。

如何编写查询以便我的所有链接显示结果?

class events_api extends Controller
{
      public function events($location = "",$event_name="",$event_status="")
    {

$events = DB::table('event_table')
            ->join('event_details', 'event_table.event_id', '=', 'event_details.event_id')
            ->join('venue', 'event_details.venue_id', '=', 'venue.venue_id')
            ->where('venue.venue_city','=',$location)
            ->where('event_table.event_name','=','$event_name')
            ->where('event_table.event_status','=','$event_status')
            ->where('event_table.event_post_status','=','publish')
  ->select('event_table.event_title','event_details.event_start_ts','event_details.event_views','venue.venue_name','venue.venue_city','venue.venue_location')
            ->get();

           echo $events;
    }
}``

1 个答案:

答案 0 :(得分:1)

如果您想使用toSql方法创建子查询:

class events_api extends Controller
{
      public function events($location = "",$event_name="",$event_status="")
      {
          $subQuery = DB::table('event_table')
              ->join('event_details', 'event_table.event_id', '=', 'event_details.event_id')
              ->join('venue', 'event_details.venue_id', '=', 'venue.venue_id')
              ->where('venue.venue_city','=',$location)
              ->where('event_table.event_name','=','$event_name')
              ->where('event_table.event_status','=','$event_status')
              ->where('event_table.event_post_status','=','publish')
              ->select('event_table.event_title','event_details.event_start_ts','event_details.event_views','venue.venue_name','venue.venue_city','venue.venue_location');

         DB::table(DB::raw("{$subQuery->toSql()} as main_query"))
             ->mergeBindings($subQuery->getBindings())
         // build your query here
             ->get()
    }
}

如果在子查询中使用任何绑定,您还需要mergeBindings