Laravel eloquent 给出与 DB 外观不同的结果

如何解决Laravel eloquent 给出与 DB 外观不同的结果

我有一个 laravel eloquent 查询,它给了我与使用 DB 门面的同一个查询不同的结果。我不明白为什么结果会不同。结果集的长度相同 (6),但一个数据对象键 ha 对于 eloquent 查询保持不变(这是不正确的),而 DB Facade 返回 {{1} } 键值正确。
雄辩:

ha

eloquent 查询返回 6 个对象项的集合,但 $add = FertilAppUser::join('farms','fertilappuser.farm_id','=','farms.id') ->join('farm_blocks','farms.id','farm_blocks.farm_id') ->crossJoin('crops','farm_blocks.crop_id','crops.id') ->select('fertilappuser.block_id','fertilappuser.id','farm_blocks.hectares as ha') ->where('fertilappuser.farm_id',16) ->whereNotIn('fertilappuser.block_id',[6]) ->groupBy('fertilappuser.id') ->get(); 键保持不变:

ha

数据库门面:

                    Collection {
                        #items: array:6 [
                          0 =>  {
                            #original: array:3 [
                              "block_id" => 140
                              "id" => 7
                              "ha" => 2.5 // does not vary
                            ]
                          }
                          1 =>  {
                            #original: array:3 [
                              "block_id" => 809
                              "id" => 66
                              "ha" => 2.5 // does not vary
                            ]
                          }
                          2 =>  {
                            #original: array:3 [
                              "block_id" => 152
                              "id" => 67
                              "ha" => 2.5 // does not vary
                            ]
                          }
                          3 =>  {
                            #original: array:3 [
                              "block_id" => 143
                              "id" => 68
                              "ha" => 2.5 // does not vary
                            ]
                          }
                          4 =>  {
                            #original: array:3 [
                              "block_id" => 149
                              "id" => 69
                              "ha" => 2.5 // does not vary
                            ]
                          }
                          5 =>  {
                            #original: array:3 [
                              "block_id" => 673
                              "id" => 70
                              "ha" => 2.5 // does not vary
                            ]
                          }
                        ]
                      }

$add = DB::select('SELECT fau.id id,fau.block_id,frm_b.hectares ha ' . ' FROM fertilappuser as fau ' . ' INNER JOIN farms AS f ' . ' ON (fau.farm_id = f.id) ' . ' INNER JOIN farm_blocks as frm_b CROSS JOIN crops c ' . ' ON (fau.block_id = frm_b.id AND frm_b.crop_id = c.id) ' . ' WHERE fau.farm_id = ? AND fau.block_id NOT IN (?) ' . ' GROUP BY fau.id ',[16,'6']); 门面返回一个长度为 6 的数组,关联的对象键 DB 值各不相同并且是正确的。

ha

有谁知道为什么会有不同的结果?我对 eloquent 查询的连接可能不正确吗?

Laravel 5.6.39

解决方法

您的 eloquent 查询转换为以下 SQL 代码:

select
    `fertilappuser`.`block_id`,`fertilappuser`.`id`,`farm_blocks`.`hectares` as `ha`
from
    `fertilappuser`
inner join
    `farms` on `fertilappuser`.`farm_id` = `farms`.`id`
inner join
    `farm_blocks` on `farms`.`id` = `farm_blocks`.`farm_id`
cross join
    `crops` on `farm_blocks`.`crop_id` = `crops`.`id`
where
    `fertilappuser`.`farm_id` = ?
and
    `fertilappuser`.`block_id` not in (?)
group by
    `fertilappuser`.`id`

您的 SQL 在某些部分有所不同:

  1. (可能的罪魁祸首)' INNER JOIN farm_blocks as frm_b CROSS JOIN crops c ' .
  2. (可能不太重要)您传递的是 '6' 而不是 6
  3. (根本不重要)别名

现在,我不确定哪个查询是正确的,但基本上不同的查询意味着不同的结果。


仅使用控制台 (php artisan tinker) 我就能够生成以下查询(不需要设置,因为我实际上没有访问任何数据库)

select
    `fau`.`id` as `id`,`fau`.`block_id`,`frm_b`.`hectares` as `ha`
from
    `fertilappuser` as `fau`
inner join
    `farms` as `f` on (
        `fau`.`farm_id` = `f`.`id`
    )
inner join
    `farm_blocks` as `frm_b`
cross join
    `crops` as `c` on (
        `fau`.`block_id` = `frm_b`.`id` and `frm_b`.`crop_id` = `c`.`id`
    )
where `fau`.`farm_id` = ?
and `fau`.`block_id` not in (?)
group by `fau`.`id`

通过运行此代码:

// You should be able to replace the first line by either
// DB::table('fertilappuser','fau')
// or FertilAppUser::from('fertilappuser','fau')
// to keep the alias
DB::connection('mysql')->table('fertilappuser','fau')
    ->select('fau.id as id','fau.block_id','frm_b.hectares as ha')
    ->join('farms as f',function ($join) {
        return $join->on(['fau.farm_id' => 'f.id']);
    })
    ->join('farm_blocks as frm_b',function ($join) {
        return $join;
    })
    ->crossJoin('crops as c',function ($join) {
        return $join->on(['fau.block_id' => 'frm_b.id','frm_b.crop_id' => 'c.id']);
    })
    ->where('fau.farm_id',16)
    ->whereNotIn('fau.block_id',['6']) // I still think this should be just 6
    ->groupBy('fau.id')
    ->toSql(); // replace with ->get(); to get the results

这里有些奇怪的东西:

  • 在 $joins 中使用数组符号。

通常你会写

$join->on(['fau.farm_id' => 'f.id'])

$join->on(['fau.block_id' => 'frm_b.id','frm_b.crop_id' => 'c.id'])

作为

$join->on('fau.farm_id','f.id')

$join->on('fau.block_id','frm_b.id')->on('frm_b.crop_id','c.id')

但是使用数组符号告诉 eloquent 在它周围放一对括号。我不确定它是否真的有助于您的查询,但我希望它完全相同。

  • 没有inner join的{​​{1}}

由于 Eloquent 强制您在使用 on 方法时添加条件,因此我只是传递了一个闭包并使其返回 join() 本身而不添加任何内容。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res