【问题标题】:Translating MySQL query into Laravel将 MySQL 查询翻译成 Laravel
【发布时间】:2015-11-07 22:43:31
【问题描述】:

我有一个 Web 应用程序,它目前使用 PHP 对存储在 MySQL 数据库中的一些数据进行排序。我目前正在使用 Laravel 框架来增强应用程序,但在将所有各种 MySQL 命令等同于 Laravel 中 DB 使用的命令时遇到了麻烦。

我有一个表,其中有一些重复的 author 名称,并且想要对这些重复的 citations 列值求和。因此,例如,表中可能有两位作者,名为John Doe,一位使用30 引用,另一位使用20。运行当前查询后,我将有两行 John Doe,两者都有 50 引用。然后我使用GROUP BY 只获取作者的一个实例。这是我的 PHP 代码中的当前查询:

// sum citations for duplicate authors
mysqli_query($connect, "UPDATE searchresponse AS r JOIN(SELECT author, SUM(citations) AS citations, COUNT(author) AS n FROM searchresponse GROUP BY author) AS grp ON grp.author = r.author SET r.citations = grp.citations");

现在我一直在尝试以下方法,但我不确定如何在 Laravel 中复制 ASSET 之类的命令:

// select relevant data
$sumData = DB::table('searchresponse')
    -> (something);
// insert selected data into table
foreach ($sumData as $value) {
    DB::table('searchresponse')->insert(
        [
            'author'   => $value->author,
            'citations => $value->citations
        ]
    );
}

基本上,我需要知道在 Laravel 中如何引用表 AS,以便我可以将其与自身进行比较,就像在我的原始方法中引用 searchresponse AS r 一样。或者,事实上,只是如何在 Laravel 中复制我原来的 PHP MySQL 查询。

编辑

正在努力,这似乎更像是我需要做的事情:

// sum citations for duplicate authors
function sumCites($data) {
    $sumAll = DB::table('searchresponse')
        ->join('searchresponse', 'searchresponse.citations', '=', 'searchresponse.citations')
        ->where('searchresponse.author', '=', 'searchresponse.author')
        ->get();
}

但我仍然收到错误

【问题讨论】:

    标签: php mysql laravel-5 database-schema


    【解决方案1】:

    尝试以下方式获取数据:

    function sumCites($data){
         // Update first
         \DB::update('UPDATE searchresponse AS r 
         JOIN(
            SELECT author, SUM(citations) AS citations, COUNT(author) AS n FROM    searchresponse GROUP BY author
           ) grp 
           ON grp.author = r.author 
           SET r.citations = grp.citations');
    
         //Now fetch all data from that table
         $sumAll = \DB::table('searchresponse')->get();
         return $sumAll;
    }
    

    如果你想更新表,你可以直接使用你的sql

    【讨论】:

    • 谢谢,但不幸的是,这不起作用。运行该函数后,表中的数据保持不变。
    • 我不需要在某处使用update 来更新表中的数据,还是应该由join 处理?
    • 请再试一次。我更新了功能。如果您遇到任何错误,请告诉我。
    • 谢谢,暂时离开我的电脑,但明天试试。一个简单的问题:DB 之前的 \ 表示什么?
    【解决方案2】:

    您正在加入同一个表,因此您需要使用表别名进行连接,请尝试以下操作:

    // sum citations for duplicate authors
    function sumCites($data) {
        $sumAll = DB::update('searchresponse')
            ->join('searchresponse as b', 'searchresponse.citations', '=', 'b.citations')
            ->where('searchresponse.author', '=', 'b.author')
            ->get();
    }
    

    【讨论】:

    • 谢谢,但由于某种原因这不起作用。表中的数据不会改变...
    • 我不需要update 来更新表中的数据吗?
    • 原来的查询好像是选择数据,如果你更新,你必须更新某些列。让我知道你想做什么,我会更新查询。
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 2020-06-03
    • 2019-05-09
    • 1970-01-01
    • 2019-08-16
    • 2015-12-13
    • 2014-07-26
    • 2011-01-01
    相关资源
    最近更新 更多