本篇文章给大家带来的内容是关于Laravel关联模型中has和with区别(详细介绍),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

首先看代码:

1

2

3

4

5

6

$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的所有数据(如果为空该条数据就不返回)。

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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的数据都是会列出的。

链接:https://pan.baidu.com/s/1v5gm7n0L7TGyejCmQrMh2g 提取码:x2p5

免费分享,但是X度限制严重,如若链接失效点击链接或搜索加群 群号518475424

它会有两条sql查询,第一条查主数据,第二条查关联,这里第二条sql如下:

1

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()后的代码如下

1

2

3

4

5

6

7

$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:

1

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区别(详细介绍)的详细内容。

Laravel关联模型中has和with区别的更多相关文章

  1. Laravel关联模型中过滤结果为空的结果集(has和with区别)

    首先看代码: $userCoupons = UserCoupons::with(['coupon' => function($query) use($groupId){ return $quer ...

  2. ThinkPHP 关联模型中查询某条记录的父级(非查询子级)

    数据表 id      cat_name      cat_pid 76     手机.数码     0 84     手机配件        76 86     蓝牙耳机        84 从属关 ...

  3. 关联模型中如果condition条件

    在练习中,有一个user表和地址表,一对多的关系. 我的想法是,通过这个关联模型找出这个用户下面默认值字段为1的地址 控制器中 public function index(){ $User = D(' ...

  4. Laravel从模型中图片的相对路径获取绝对路径

    在模型product.php中增加以下方法.数据库图片字段为image.存储的图片相对路径 public function getImageUrlAttribute() { // 如果 image 字 ...

  5. laravel为模型中所有查询统一添加WHERE条件

    在使用laravel开发web系统的过程,需要在model处为该模型统一添加一个条件或者多个条件,研究了一个laravel的模型类,发现model中有个方法是构建查询的,方法如下: /** * Reg ...

  6. Laravel关联模型

    public $timestamps = false;//不存时间 1.多对多关联.如收藏.用户表users,产品表products,收藏中间表user_favorite_products.那么在用户 ...

  7. laravel 强大的关联模型

    内容比较多,不总结了,直接看学院君的译文吧,已经写得很详细了 传送门:http://laravelacademy.org/post/6191.html PS1: laravel的关联模型并不是遍历一次 ...

  8. Django模型中OneToOneField和ForeignKey的区别

    网上看到一篇讲解"Django模型中OneToOneField和ForeignKey区别" 的文章,浅显易懂; 可以把ForeignKey形象的类比为: ForeignKey是on ...

  9. ThinkPHP第十四天(显示TRACE界面配置,关联模型详解定义)

    1.显示TRACE界面,首选需要在显示模版界面,$this->display(),然后需要在配置文件中配置 SHOW_PAGE_TRACE => true 2.关联模型使用 主表以user ...

随机推荐

  1. asp.net mvc4 bundle添加带min的js问题

    今天在用ScriptBundle的时候发现js文件有min的,无法bundle进去,具体我也不知道怎么回事. @Tony Tan 回复:bundles.IgnoreList可以设置 去除min.js的 ...

  2. win7搭建本地SonarQube环境进行c#代码分析

    1.SonarQube需要正常运行,首先需要安装Java环境,我这里安装的是jdk-8u181版本,可以在下面网站找适的版本去下载安装 https://www.oracle.com/technetwo ...

  3. 【maven】测试

    针对spring-boot项目 通过命令行执行mvn命令来启动测试模块. 1.引入plugin 并自定义参数ignore.test 2.命令行传递参数启动test mvn clean package ...

  4. QT4.8.7和VS2010环境搭建及使用

    (一)环境搭建 首先下载QT4.8.7的安装包.QT Addin 1.11插件和VS2010安装包.第一步:安装好VS2010第二步:安装QT4.8.7(qt-opensource-windows-x ...

  5. 怎么把使用vuepress搭建的博客部署到Github Pages

    推荐在这里阅读效果更佳 背景 网上搜了很多教程,包括官网的教程,但是还是费了一番功夫, 如果你使用自动化部署脚本部署不成功的话,可以参考我的这个笨方法 这是部署后的效果 前提 我假设你本地运行OK, ...

  6. pandas 之 datetime 初识

    import numpy as np import pandas as pd 认识 Time series data is an impotant from of data in many diffe ...

  7. linux驱动学习笔记---实现中断下半部以及驱动编写规范(七)【转】

    转自:https://blog.csdn.net/weixin_42471952/article/details/81609141 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协 ...

  8. 3-6 merge操作

    In [1]: import pandas as pd In [6]: left =pd.DataFrame({ 'A':['A0','A1','A2','A3'], 'B':['B0','B1',' ...

  9. Ubuntu 18.04通过命令禁用/开启触控板

    Ubuntu下经常遇到无法用快捷键关闭触控板的情况,博主的电脑安装Ubuntu18.04后便出现了该问题. 解决办法: 首先查看输入设备的id,命令行输入: xinput ,插鼠标与不插鼠标时,Tou ...

  10. promise 的基本用法

    //知识点1 例1--- 最基本的写法 Promise的基本语法哦 const Aa=new Promise(function(resolve,reject){ //resolve和reject是参数 ...