简体   繁体   中英

How to select all the values from a table except the values which are in foreign table?

I have three tables: tbl_borrower, tbl_client and tbl_guarantor

tbl_Client:
    id|name|address|email|

tbl_Guarantor:
    id|clientid(fk)|Guaranteed_date|borrower_id(fk from borrower table)

I want to retrieve all the values of client table except the values which are present in guarantor table in the controller of Laravel 5.5 .

Once you have the models and relationships set up, you should just do:

Client::doesntHave('guarantor')->get()

https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-absence

If you're using the query builder, it would be:

 $clients = DB::table('tbl_clients')
        ->join('tbl_guarantor', 'tbl_clients.id', '=', 'tbl_guarantor.clientid')
        ->select('tbl_clients.*')
        ->whereNull('tbl_guarantor.clientid')
        ->get();

https://laravel.com/docs/5.5/queries

With the premise of using a left join and testing for NULL on the 2nd table id based on this answer. https://stackoverflow.com/a/4076157/3585500

Try this :

DB::table('tbl_Client')
      ->groupBy('tbl_Client.id')                           
      ->leftjoin('tbl_Guarantor', 'tbl_Client.id', '=', 'tbl_Guarantor.clientid')                           
      ->get([
           'tbl_Client.*'
       ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM