duanfen9090 2019-03-04 08:45 采纳率: 100%
浏览 80
已采纳

如何使用DB Facades访问数据库?

Per the documentation we can do something like this to run a raw query :

use Illuminate\Support\Facades\DB;

DB::select('select * from users where id = :id', ['id' => 1]);

But I couldn't find a way in the documentation to initialize eloquent with my database in order to execute that query.

I'm using PHP 7.3 (no frameworks) to work with eloquent. Where can I initialize the database to eloquent?

I've found in the doc ways to do so using the \Capsule\Manager as seen in the readme in this link, but no way to use this while getting the Db::select to work, any idea on how to properly configure this?

I'm looking for something like this maybe ?

DB::init([
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => ''
])
  • 写回答

2条回答 默认 最新

  • dongqiao1151 2019-03-04 09:11
    关注

    I've found another way to use raw queries using the capsule manager directly :

    use Illuminate\Database\Capsule\Manager as DB;
    
    $capsule = new DB;
    $capsule->addConnection([
        'driver' => 'mysql',
        'host' => DB_SERVER,
        'database' => DB_DATABASE,
        'username' => DB_SERVER_USERNAME,
        'password' => DB_SERVER_PASSWORD,
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        ]);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    
    $test = DB::select('select * from products where products_id = :id', ['id' => 19536]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile