2

How to do a inner query in laravel. Please consider that my issue is other than this question.

I have a common method that returns both common and complex inner query. With it, I've found a dirty fix reading laravel's source code

$query->whereIn('column', function ($query) { /*noop*/ });
$innerQuery = Model::myComplexInnerQueryMethod()->getQuery();
$query->getQuery()->wheres[0]['query'] = $innerQuery;
$query->mergeBindings($innerQuery);

But this is ugly (to say the least) Any thoughts?

Update for martin's answer
class MyModel extends \Eloquent {
    // @return \Illuminate\Database\Query\Builder
    static function myComplexInnerQueryMethod($index) {
        return static::query()->join(…)->join(…)->where(…)->where(…)->etc();
    }
}

class Analytics extends MyModel {
    function scopeIndex($query, $index) {
        $query->whereIn('column', function ($query) { /*noop*/ });
        $innerQuery = self::myComplexInnerQueryMethod($index)->getQuery();
        $query->getQuery()->wheres[0]['query'] = $innerQuery;
        $query->mergeBindings($innerQuery);
        return $query;
    }
}
Alwin Kesler
  • 1,450
  • 1
  • 20
  • 41
  • I know I can extend `\Illuminate\Database\Query\Builder`. In this riddle this is not an option ;) – Alwin Kesler Jun 29 '17 at 13:15
  • I suggest passing an optional `$query` parameter to `myComplexInnerQueryMethod` and instead of creating a new query, just updating the given query (if any) and returning the updated/new query. – apokryfos Jun 29 '17 at 13:16
  • hmm. Nice point @apokryfos – Alwin Kesler Jun 29 '17 at 13:17
  • Have you read Laravel’s documentation on queries? It’s entirely possible to perform simple and complex joins out the box with the query builder: https://laravel.com/docs/4.2/queries#joins – Martin Bean Jun 29 '17 at 13:17
  • Yes @MartinBean, but I need to use anonymous function's inner query. I can't pass a custom query created outside that scope – Alwin Kesler Jun 29 '17 at 13:19
  • I don’t understand what it is your trying to do. Why not tell us _what_ you’re trying to do rather than _how_ you’re trying to accomplish it? – Martin Bean Jun 29 '17 at 13:20
  • Do you mean a subquery? Or an inner join? – schellingerht Jun 29 '17 at 13:22

0 Answers0