1、在保证当前环境已安装好mongodb扩展的前提下,在项目vendor目录同级,使用composer安装库
composer require jenssegers/mongodb ^3.6 -vvv
2、注册服务,在config\app.php文件里的providers
数组末尾追加一行配置
Jenssegers\Mongodb\MongodbServiceProvider::class
3、注册facede,在config\app.php文件里的aliases
数组末尾追加一行配置
'Mongo' => Jenssegers\Mongodb\MongodbServiceProvider::class
4、配置mongo连接,在config\database.php文件里的mysql
数组同级,增加一个数组配置,如下
'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], 'mongodb' => [ 'driver' => 'mongodb', 'host' => env('MONGO_DB_HOST', '地址'), 'port' => env('MONGO_DB_PORT', '3717'), 'database' => env('MONGO_DB_DATABASE', 'demo'), 'username' => env('MONGO_DB_USERNAME', 'user60301726'), 'password' => env('MONGO_DB_PASSWORD', '1907aA123@'), ], 复制代码
5、定义mongo模型类,引用Illuminate\Support\Facades\DB
,实现方式与mysql操作一致。基本操作如下
<?php namespace App\Model\MongoDb; use Illuminate\Support\Facades\DB; class Base { protected static $connection = 'mongodb'; protected static $table = 't1'; /** * 写入数据 * * @return void */ public static function insert($data){ return DB::connection(static::$connection)->collection(static::$table)->insert($data); } public static function delete($where){ return DB::connection(static::$connection)->collection(static::$table)->where($where)->delete(); } public static function update($where, $update){ return DB::connection(static::$connection)->collection(static::$table)->where($where)->update($update); } public static function paginate($queryDataRaw=[], $page=1, $pageSize=10, $orderBy=[]){ $collection = DB::connection(static::$connection)->collection(static::$table); $count = $collection->count(); // // return $count; $list = []; if( $count > 0 ){ if($orderBy){ foreach($orderBy as $field=>$sort){ $collection = $collection->orderBy($field, $sort); } } $offset = $pageSize*($page-1); $collection = $collection->offset($offset)->limit($pageSize)->get(); foreach($collection as $record){ $list[] = $record; } } return [ 'count'=> $count, 'list'=> $list, ]; } } 复制代码
或者
$data = DB::connection('mongodb') ->table('t1') ->get()->toArray(); print_r($data);die; 复制代码
网络异常,图片无法展示
|