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.

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

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式