一、在项目的根目录执行命令
composer require jenssegers/mongodb
二、在\config\app.php中注册服务
'providers' => [
Jenssegers\Mongodb\MongodbServiceProvider::class,//mongodb
],
'aliases' => [
'Mongo' => Jenssegers\Mongodb\MongodbServiceProvider::class, //mongodb
],
三、修改数据库配置文件 config/database.php
'connections' => [
// 添加如下配置
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGO_DB_HOST', ''),
'port' => env('MONGO_DB_PORT', 27017),
'database' => env('MONGO_DB_DATABASE',''),
'username' => env('MONGO_DB_USERNAME',''),
'password' => env('MONGO_DB_PASSWORD',''),
],
],
五、env文件中添加如下配置
MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=admin
MONGO_DB_USERNAME=yang
MONGO_DB_PASSWORD=666666
六、创建 demo 模型 (我这里面继承了一个 BaseMongo 类)
BaseMongo.php
<?php
namespace Common\MongodbModel;
use Jenssegers\Mongodb\Eloquent\Model;
class BaseMongo extends Model
{
protected $connection = 'mongodb';//等价于数据库
/*public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}*/
}
MongoDemo.php
<?php
namespace Common\MongodbModel;
class MongoDemo extends BaseMongo
{
//这是一个demo
protected $collection = 'demo'; //等价于数据表
protected $guarded = []; //设置字段白名单
protected $primaryKey = '_id'; //设置id
protected $dates = ['deleted_at'];
}
七、添加与获取
MongoDB视图工具查看存入结果
PHP打印获取结果
<?php
namespace Modules\Admin\Http\Controllers;
use Common\MongodbModel\MongoDemo;
use App\Http\Controllers\Controller;
class IndexController extends Controller
{
public function menu()
{
MongoDemo::insert(['name'=>'yang','sex'=>'男', 'age'=> 28]);//存入
$res = MongoDemo::take(5)->get()->toarray(); //取出
//$user = MongoDemo::find('5f44bbe2f6966e1de4005b52')->toArray();//根据id取出
dd($res);
}
}