Search code examples
laravelgraphqllaravel-lighthouse

GraphQL Where Select Sub Query


These day, i have studied GraphQL with Laravel framework, Lighthouse Library. I have tried to do kind of SELECT Query.

As a result, I wonder GraphQL can select below SQL Query

SELECT * FROM TABLE_A WHERE type=1 AND chart_id=(SELECT id FROM TABLE_B WHERE phone='0000~~')

I expect, Client first get result from this query.

SELECT id FROM TABLE_B WHERE phone='0000~~'

And then Do Second query, i think i can get a result.

But i wonder I can get result from 1 request. Thanks.


Solution

  • You can try following

     $phoneNumber = '0000~~';
    
     $data = DB::table('tableA')->where('type',1)
                ->whereIn('chart_id',function($query) use ($phoneNumber) {
                    $query->select('id')
                          ->from('tableB')
                         ->where('phone', '=',$phoneNumber);
             })->get();
    

    If there is relationship between tableA and tableB you can do following

     TableA::where('type',1)
            ->whereHas('tableBRelationshipName', function ($q) use ($phoneNumber) {
                 $q->select('id')
                 $q->where('phone','=',$phoneNumber);
     })->get();