搜索
首页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

taskManagementtoolSareessential forefectiverMototeprojectManagementbyPrioritizingTaskSandTrackingProgress.1)usetoolsliketrelliketreloandasanatosetprioritieswithlabelsortags.2)

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

1)itoptimizeseLizeSeloQuentModelloAdingWithlazyProxies.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)实现DataBaseShardingTodistAcribedateAtaCrossmultipledataBasesForimProvesforimpRevemperformance.2)uselaravel'scachingsystemystemystemystemystemnememmemememememcachedtebachedtorcachedtobcachebab

沉默的斗争:克服分布式团队中的沟通障碍沉默的斗争:克服分布式团队中的沟通障碍May 02, 2025 am 12:20 AM

doovercomecommunicationbarriersIndistributedTeams,使用:1)VideoCallSforface-face-Faceinteraction,2)setClearresponsEtimepections,3)chooseappropropraproproprapropropriatecommunicationTools,4)CreatseateAteAteAteamCommunicationGuide和5)建立PemersonalboundariestariestopreventBreventBurniationBurnication.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和perperatefulfeatures.1)UseeloquentormForintuiveDiendbackendDatamanipulation,butavoidn 1Queryissues.2)

您使用哪种工具来保持远程角色保持连接?您使用哪种工具来保持远程角色保持连接?May 01, 2025 am 12:21 AM

forremotework,iusezoomforvideOcalls,Slackformessing,trelloforprojectmanagement,and gitgithubForCodeCollaboration.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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。