Ad

Laravel Subquery To Another Database Table

- 1 answer

I need to subquery where data doesn't exist in another db table.

I tried with DB::connection('dbconfigname')

First DB vmysql tablename node

|id|name|
|1 |sam |
|2 |jack|
|3 |mat |
|4 |king|

Second DB mysql tablename node_tag

|id|node_id|
|1 |2 |
|2 |3 |

My query

$tag = 'true';
\DB::connection('vmysql')->table('node')->->when($tag, function($query) use($tag){
            if ($tag === 'true') {
                \DB::connection('mysql');
                $query->whereNOTIn('node.id',function($subquery){
                    $subquery->select(\DB::connection('mysql')->select(\DB::raw("select node_id from node_tag")));
     
                 });
            }
        })

Is it possible to subquery through another DB table

Ad

Answer

Yup, just need to do a join query: https://laravel.com/docs/7.x/queries#joins

Alternatively, if you have eloquent models, you could do

$nodeTags = NodeTag::distinct('node_id')->get()->toArray();
$nodesWithoutTags = Node::whereNotIn('id', $nodeTags)->get();
Ad
source: stackoverflow.com
Ad