搜尋
首頁php框架LaravelLaravel關聯模型中has和with區別(詳細介紹)

這篇文章帶給大家的內容是關於Laravel關聯模型中has和with區別(詳細介紹),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

首先看程式碼:

$userCoupons = UserCoupons::with(['coupon' => function($query) use($groupId){
    return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([
        'group_id' => $groupId,
    ]);
}])
// 更多查询省略...

資料結構是三張表使用者優惠券表(user_coupons)、優惠券表(coupons),商家表(corps),群組優惠券表(group_coupons) (為了方便查看,後兩項已去除)

這裡我本意想用模型關聯查出用戶優惠券中屬於給定組gourpId的所有數據(如果為空該條數據就不返回)。

但有些結果不是我想要的:

  array(20) {
    ["id"]=>
    int(6)
    ["user_id"]=>
    int(1)
    ["corp_id"]=>
    int(1)
    ["coupon_id"]=>
    int(4)
    ["obtain_time"]=>
    int(1539739569)
    ["receive_time"]=>
    int(1539739569)
    ["status"]=>
    int(1)
    ["expires_time"]=>
    int(1540603569)
    ["is_selling"]=>
    int(0)
    ["from_id"]=>
    int(0)
    ["sell_type"]=>
    int(0)
    ["sell_time"]=>
    int(0)
    ["sell_user_id"]=>
    int(0)
    ["is_compose"]=>
    int(0)
    ["group_cover"]=>
    string(0) ""
    ["is_delete"]=>
    int(0)
    ["score"]=>
    int(100)
    ["created_at"]=>
    NULL
    ["updated_at"]=>
    NULL
    ["coupon"]=>
    NULL  // 注意返回了coupons为空的数据
  }

記錄中有的coupon有記錄,有的為空。想想也是,with只是用sql的in()實作所謂的預先載入。無論怎樣主user_coupons的資料都是會列出的。

它會有兩個sql查詢,第一個查主數據,第二個查關聯,這裡第二個sql如下:

select `id`, `group_id`, `cover`, `group_number`, `group_cover` from `youquan_coupons` where `youquan_coupons`.`id` in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14) and (`group_id` = 1) and `youquan_coupons`.`deleted_at` is null

如果第二個為空,主記錄的關聯欄位就是NULL。

後來看到了Laravel關聯的模型的has()方法,has()是基於存在的關聯查詢,下面我們用whereHas()(一樣作用,只是更高級,方便寫條件)

這裡我們思想是把判斷有沒有優惠券資料也放在第一次查詢邏輯中,所以才能實現篩選空記錄。

加上whereHas()後的程式碼如下

    $userCoupons = UserCoupons::whereHas('coupon', function($query) use($groupId){
            return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([
                'group_id' => $groupId,
            ]);
        })->with(['coupon' => function($query) use($groupId){
            return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover');
        }])-> // ...

看下最終的SQL:

select * from `youquan_user_coupons` where exists (select `id`, `group_id`, `cover`, `group_number`, `group_cover` from `youquan_coupons` where `youquan_user_coupons`.`coupon_id` = `youquan_coupons`.`id` and (`group_ids` = 1) and `youquan_coupons`.`deleted_at` is null) and (`status` = 1 and `user_id` = 1)

這裡其實是用exists()篩選存在的記錄。然後走下一步的with()查詢,因為此時都篩選一遍了,所以with可以去掉條件。

顯然區分這兩個的作用很重要,尤其是在列表中,不用特意去篩選為空的數據,而且好做分頁。

#

以上是Laravel關聯模型中has和with區別(詳細介紹)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault思否。如有侵權,請聯絡admin@php.cn刪除
任務管理工具:遠程項目的優先級和跟踪進度任務管理工具:遠程項目的優先級和跟踪進度May 02, 2025 am 12:25 AM

taskManagementsToolSareEssentialForefectiverMototeprojectManagementbyPrioritizingTaskSandTrackingProgress.1)USETOOLSLIKETRELLOANDASANATASANATOSETPRIORITIONTAGS.2)

最新的Laravel版本如何提高性能?最新的Laravel版本如何提高性能?May 02, 2025 am 12:24 AM

Laravel10enhancesPerformancEthroughSeveralKeyKeyFeatures.1)itintroducesquereBuilderCachingTordorcachingTordOuctedSataBaseload.2)itoptimiesseloizeseloquentmodelloAdingwithlazyproxies.3)

全棧Laravel應用程序的部署策略全棧Laravel應用程序的部署策略May 02, 2025 am 12:22 AM

最佳的全棧Laravel應用部署策略包括:1.零停機部署,2.藍綠部署,3.持續部署,4.金絲雀發布。 1.零停機部署使用Envoy或Deployer自動化部署過程,確保應用在更新時保持可用。 2.藍綠部署通過維護兩個環境實現無停機部署,並允許快速回滾。 3.持續部署通過GitHubActions或GitLabCI/CD自動化整個部署流程。 4.金絲雀發布通過Nginx配置,將新版本逐步推廣給用戶,確保性能優化和快速回滾。

擴展全堆棧Laravel應用程序:最佳實踐和技術擴展全堆棧Laravel應用程序:最佳實踐和技術May 02, 2025 am 12:22 AM

toscalealaravelApplication有效,焦點databaseSharding,緩存,負載平衡和microservices.1)實現DataBasEshardingTodistaCripedataCrossmultipledataBasesForimProvesforimPrevperformance.2)uselaravel'scachingsystemystemystemystemywithredsormememememememcachedtebachedtebab

沉默的鬥爭:克服分佈式團隊中的溝通障礙沉默的鬥爭:克服分佈式團隊中的溝通障礙May 02, 2025 am 12:20 AM

doovercomecommunicationbarriersIndistributedTeams,使用:1)VideoCallSforface-to-Faceinteraction,2)setClearresponsEtimepections,3)chooseappropropropraproproprapropropriatecommunicationTools,4)CreatseateAteAteAteamCommunicationGuide和5)建立PemersonalBoundariestAriestOpeopReventBreventBurniationBurnication.the

使用Laravel Blade在全棧項目中進行前端模板使用Laravel Blade在全棧項目中進行前端模板May 01, 2025 am 12:24 AM

laravelbladeenhancesfrontendtemplatinginflatinginflationll-stackprojectsbyferingCleanSyntaxandaxandpoperfelfulfeatures.1)itallowsforeasyvariableasyvariabledisplayandControlstructures.2)bladesuportsuportsuportscreatingingingingingingingingingingangingandredreingscomponents components components components,aidinginmanagingcomplexuis.3)

使用Laravel:實用教程構建全堆棧應用程序使用Laravel:實用教程構建全堆棧應用程序May 01, 2025 am 12:23 AM

laravelisidealforll-stackapplicationsduetoitselegantsyntax,complastissionecosystem和perperatedfulfeatures.1)useeloquentormforintuivelbackenddatamanipulation,butavoidn 1queryissues.2)

您使用哪種工具來保持遠程角色保持連接?您使用哪種工具來保持遠程角色保持連接?May 01, 2025 am 12:21 AM

forremotework,iusezoomforvideOcalls,Slackformessing,trelloforprojectmanagement,and giThubForCodeCollaboration.1)Zoomisreliable forlailible forlargemeetingsbuthastimelimitsonthefreeversion.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器