Koeno
Koeno

Reputation: 1583

Laravel query subquery

For example I have 2 queries:

1:

$q = SomeContent::select('somecontent_id')
    ->where('slug', Request::segment(2))
    ->where('something', $something)
    ->first();

2

$req = SomeContent::select('slug')
    ->where('something', $anothersomething)
    ->where('somecontent_id', $q->somecontent_id)
    ->first();

How would I merge these together as one query if possible in laravel's query builder? I can't find a lot about using selects statements inside where statements.

Upvotes: 0

Views: 66

Answers (2)

perry
perry

Reputation: 11

you could also you the orWhere function

$q = SomeContent::select('somecontent_id')
      ->where('slug', Request::segment(2))
       ->where('something', $something)
        ->orWhere(function($query)
        {
            $query->where('something', $anothersomething)
          ->where('somecontent_id', $q->somecontent_id)
           ->union($q)->get();
        })
        ->get();

Upvotes: 1

Demodave
Demodave

Reputation: 6662

You can union them together, something like

// The query builder also provides a quick way to "union" two queries together:

$q = SomeContent::select('somecontent_id')
    ->where('slug', Request::segment(2))
    ->where('something', $something);

$req = SomeContent::select('slug')
    ->where('something', $anothersomething)
    ->where('somecontent_id', $q->somecontent_id)
    ->union($q)->get();

Upvotes: 1

Related Questions