How to create a subquery using Laravel Eloquent?

前端 未结 1 1390
天命终不由人
天命终不由人 2020-11-29 07:51

I have the following Eloquent query (This is a simplified version of a query which consists of of more wheres and orWheres hence the apparent round

相关标签:
1条回答
  • 2020-11-29 07:59

    This is how you do a subquery where:

    $q->where('price_date', function($q) use ($start_date)
    {
       $q->from('benchmarks_table_name')
        ->selectRaw('min(price_date)')
        ->where('price_date', '>=', $start_date)
        ->where('ticker', $this->ticker);
    });
    

    Unfortunately orWhere requires explicitly provided $operator, otherwise it will raise an error, so in your case:

    $q->orWhere('price_date', '=', function($q) use ($start_date)
    {
       $q->from('benchmarks_table_name')
        ->selectRaw('min(price_date)')
        ->where('price_date', '>=', $start_date)
        ->where('ticker', $this->ticker);
    });
    

    EDIT: You need to specify from in the closure in fact, otherwise it will not build correct query.

    0 讨论(0)
提交回复
热议问题