在函数中调用 db

Calling db in a function

我正在尝试使用我在 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;
    }
}

它returns这个错误:

Slim Application Error The application could not run because of the following error:

Type: Error Message: Call to a member function get() on null

我哪里错了?

编辑

我在第一个答案后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;
    }
}

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

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

DB 全 class 名字是 \Illuminate\Support\Facades\DB
编辑
这种情况下在函数参数

中添加 $app 属性
function userScore($uid, $app) {    
    $db = $app->get('db');