非框架內使用 ORM

declandragon發表於2023-11-09

composer.json

{
    "require": {
        "php": "^7.3",
        "ext-curl": "*",
        "ext-json": "*",
        "ext-openssl": "*",
        "ext-pdo": "*",
        "ext-redis": "*",
        "guzzlehttp/guzzle": "~7.0",
        "laravel/lumen-framework": "~8.0",
        "millionmile/get_env": "~1.0"
    },
    "config": {
        "sort-packages": true
    }
}

定義一個 DB 方法

use Illuminate\Database\Capsule\Manager as Capsule;
use MillionMile\GetEnv\Env;

function bootDB()
{
    $capsule = new Capsule();
    $capsule->addConnection([
        'driver' => 'mysql',
        'host' => Env::get('DB_HOST'),
        'port' => Env::get('DB_PORT'),
        'database' => Env::get('DB_DATABASE'),
        'username' => Env::get('DB_USERNAME'),
        'password' => Env::get('DB_PASSWORD'),
        'charset' => Env::get('DB_CHARSET'),
    ]);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
}

在任意地方使用

use Illuminate\Database\Capsule\Manager as DB;

bootDB();

$list = DB::table('table')->where('where', '')->limit(5)->distinct()->pluck('oid')->toArray();

dump($list);
本作品採用《CC 協議》,轉載必須註明作者和本文連結
感謝閱讀,有收穫的話不妨點個贊:smiling_imp:

相關文章