【问题标题】:How to select all the values from a table except the values which are in foreign table?如何从表中选择除外表中的值之外的所有值?
【发布时间】:2026-01-04 13:50:01
【问题描述】:

我有三张桌子:tbl_borrower, tbl_clientandtbl_guarantor

tbl_Client:
    id|name|address|email|

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

我想检索客户表的所有值,除了Laravel 5.5控制器的担保人表中存在的值。

【问题讨论】:

    标签: php mysql laravel laravel-5


    【解决方案1】:

    一旦你建立了模型和关系,你应该这样做:

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

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

    【讨论】:

      【解决方案2】:

      如果您使用的是查询生成器,则为:

       $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

      在使用左连接并根据此答案在第二个表 id 上测试 NULL 的前提下。 https://*.com/a/4076157/3585500

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】: