本篇文章给大家带来的内容是关于laravel关联模型中has和with区别(详细介绍),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
首先看代码:
1
2
3
4
5
6
$urcoupons = urcoupons::with(['coupon' => function($query) u($groupid){
return $query->lect('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([
'group_id' => $groupid,
]);
}])
// 更多查询省略...
数据结构是三张表用户优惠券表(ur_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)
["ur_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_lling"]=>
int(0)
["from_id"]=>
int(0)
["ll_t英语音节是什么ype"老子名言]=>
int(0)
["ll_time"]=>
int(0)
["ll_ur_id"]=>
int(0)
["is_compo"]=>
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()实现的所谓预加载。无论怎样主ur_coupons的数据都是会列出的。
它会有两条sql查询,第一条查主数据,第二条查关联,这里第二条sql如下:
1
lect `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
$urcoupons = urcoupons::wherehas('coupon', function($query) u($groupid){
return $query->lect('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([
'group_id' => $groupid,
]);
})->with(['coupon' => function($query) u($groupid){
return $query->lect('id', 'group_id', 'cover', 'group_number', 'group_cover');
}])-> // ...
看下最终的sql:
1
lect * from `youquan_ur_coupons` where exists (lect `id`, `group_id`, `cover`, `group_number`, `group_cover` from `youquan_coupons` where `youquan_ur_coupons`.`coupon_id` = `youquan_coupons`.`id` and (`group_ids` = 1) and `youquan_coupons`.`deleted_at` is null) and (`status` = 1 and `ur_id` = 1)
这里实际上是用exists()筛选存在的记录。然后走下一步的with()查询,因为此时都筛选一遍了,所以with可以去掉条件。
显然区分这两个的作用很重要,尤其是在列表中,不用特意去筛选为空的数据,而且好做分页。
以上就是laravel关联模型中has和with区别(详细介绍)的详细内容。
本文发布于:2023-04-07 19:53:56,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/52d16a1d248e86ca6b46abe718b5d4d5.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Laravel关联模型中has和with区别.doc
本文 PDF 下载地址:Laravel关联模型中has和with区别.pdf
| 留言与评论(共有 0 条评论) |