dongren1011 2016-05-02 15:37
浏览 165
已采纳

为什么Laravel调用execute()会返回重复的结果?

I'm a new, inexperienced Laravel developer and I'm confused by the query results I'm getting. I'm trying to write to results of a query to a CSV file. My code:

$connection = fopen('/BSTablespace/someFile.txt', 'w');

$users = DB::table('users')->select('first_name', 'agent_id_from_website', 'sales_manager_id', 'last_name')->toSql();

$generator = function () use ($users){
        $db = DB::connection()->getPdo();

        $query = $db->prepare($users);
        $query->execute();

        while($user = $query->fetch()){
            yield($user);
        }
    };

foreach ($generator() as $g){
        fputcsv($connection, array_values($g));
    }
fclose($connection);

Instead of getting one result per column, I get 2. One keyed with the column name and one keyed with a numeric index, like so:

'first_name' => 'Jane', 0 => 'Jane', 'agent_id_from_website' => '450', 1 => '450', 'sales_manager_id' => 317, 2 => 317, 'last_name' => 'Doe', 3 => 'Doe'

Why am I getting duplicate results? Obviously I can just ignore the duplicates but I'm very curious as to why PHP, Laravel, or Postgres handles it this way.

  • 写回答

1条回答 默认 最新

  • dongtan9465 2016-05-02 15:42
    关注

    Why are you not just doing ->get()? You're getting weird results because that's how the PHP PDO works. These \Illuminate\DB methods you're using are basically touching the PDO directly.

    http://php.net/manual/en/pdostatement.fetch.php

    It returns both the sequential values and the given name of the statement. This is probably to deal with instances where there are unnamed columns returned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?