MongoDB
webman默認使用 mongodb/laravel-mongodb 作為mongodb組件,它是從laravel項目中抽離出來的,用法與laravel相同。
使用jenssegers/mongodb
之前必須先給php-cli
安裝mongodb擴展。
注意
當前手冊為 webman v2 版本,如果您使用的是webman v1版本,請查看 v1版本手冊
使用命令php -m | grep mongodb
查看php-cli
是否裝了mongodb擴展。注意:即使你在php-fpm
安裝了mongodb擴展,不代表你在php-cli
可以使用它,因為php-cli
和php-fpm
是不同的應用程序,可能使用的是不同的php.ini
配置。使用命令php --ini
來查看你的php-cli
使用的是哪個php.ini
配置文件。
安裝
composer require -W webman/database mongodb/laravel-mongodb ^4.8
安裝后需要restart重啟(reload無效)
配置
在 config/database.php
里增加 mongodb
connection, 類似如下:
return [
'default' => 'mysql',
'connections' => [
...這里省略了其它配置...
'mongodb' => [
'driver' => 'mongodb',
'host' => '127.0.0.1',
'port' => 27017,
'database' => 'test',
'username' => null,
'password' => null,
'options' => [
// here you can pass more settings to the Mongo Driver Manager
// see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters that you can use
'appname' => 'homestead'
],
],
],
];
示例
<?php
namespace app\controller;
use support\Request;
use support\Db;
class UserController
{
public function db(Request $request)
{
Db::connection('mongodb')->table('test')->insert([1,2,3]);
return json(Db::connection('mongodb')->table('test')->get());
}
}
模型示例
<?php
namespace app\model;
use DateTimeInterface;
use support\MongoModel as Model;
class Test extends Model
{
protected $connection = 'mongodb';
protected $table = 'test';
public $timestamps = true;
/**
* @param DateTimeInterface $date
* @return string
*/
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format('Y-m-d H:i:s');
}
}