【问题标题】:Calling db in a function在函数中调用 db
【发布时间】:2018-07-05 14:34:34
【问题描述】:

我正在尝试使用我在 routes.php 文件中编写的函数:

函数是这样的:

function userScore($uid) {

    $db = $app->get('db');

    //calcolo punteggio totale 
    $query_punti = $db->table('prodotti_sounding')
    ->where('id_utente', $uid)
    ->select('punti')
    ->get();

    $totale_punti = 0;
    foreach($query_punti as $item) {
       $totale_punti += $item->punti;
    }
}

它返回此错误:

Slim 应用程序错误应用程序无法运行,因为 以下错误:

类型:错误消息:在 null 上调用成员函数 get()

我哪里错了?

编辑

我在routes.php第一个答案后的相关代码是:

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Illuminate\Database\Connection;
use Slim\Http\UploadedFile;
use Illuminate\Support\Facades\DB as DB;

$container = $app->getContainer();

$app->post('/sendbarcode', function ($request, $response){
            /* parametri barcode */
            /** @var Container $this */
            /** @var Connection $db */

            $barcode = $request->getParsedBodyParam('barcode');
            $id_utente = $request->getParsedBodyParam('id_utente');

            $db = $this->get('db');

            // prepare data for json
            $array['itacheck'] = 0;

            if(checkbarcode($barcode) == 1 ) {
                $array['it_check'] = 1;
                $array['punti'] = 25;
                $array['totalepunti'] = userScore($id_utente);
            }

            $array['barcode'] = $rows;

            if(count($rows) > 0){
                return $response->withJson($array, 200, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_LINE_TERMINATORS);
            } 
        });

function userScore($uid) {

    //calcolo punteggio totale in base alle segnalazioni pregresse
    $query_punti = DB::table('prodotti_sounding')
    ->where('id_utente', $uid)
    ->select('punti')
    ->get();

    // check total points
    $totale_punti = 0;
    foreach($query_punti as $item) {
       $totale_punti += $item->punti;
    }
}

【问题讨论】:

    标签: eloquent slim


    【解决方案1】:

    错误变为$db = $app->get('db');,因为您没有定义$app 变量。你可以使用这个

    //calcolo punteggio totale 
    $query_punti = DB::table('prodotti_sounding')
        ->where('id_utente', $uid)
        ->select('punti')
        ->get();
    

    DB 全类名是\Illuminate\Support\Facades\DB
    编辑
    这种情况在函数参数中添加$app属性

    function userScore($uid, $app) {    
        $db = $app->get('db');
    

    【讨论】:

    • 对我不起作用...在这种情况下我应该如何使用 $app 变量?
    • 类型:RuntimeException 消息:尚未设置外观根。
    • 函数在routes.php 中定义,在同一个文件中,我还有其他几个运行良好的查询
    • 我在你之前找到了一个解决方案,但是你的和我的几乎一样,但是我直接传递了$db对象。 TNX
    猜你喜欢
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2011-06-20
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多