在laravel 同時使用mongodb和MySQL
一、laravel v5.3.11
二、mongodb v3.2.29
三、jenssegers/laravel-mongodb v3.1.0-alphaphp
主要安裝jenssegers/laravel-mongodb
包mysql
一、下載對應版本laravel
"require": { "jenssegers/mongodb": "3.1.0-alpha" },
composer update
注:遇到如下報錯, 則是沒有找到PHP的mongodb擴展,請先安裝mongodb擴展後再次composergit
Your requirements could not be resolved to an installable set of packages. Problem 1 - mongodb/mongodb 1.0.3 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.0.2 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.0.1 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.0.0 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb is missing from your system. - jenssegers/mongodb v3.1.0-alpha requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1, 1.0.2, 1.0.3]. - Installation request for jenssegers/mongodb 3.1.0-alpha -> satisfiable by jenssegers/mongodb[v3.1.0-alpha].
一、config/app.php - Service Providergithub
providers追加: Jenssegers\Mongodb\MongodbServiceProvider::class, aliases追加: 'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class, //Moloquent 使用mongodb的Model繼承
二、config/database.phpsql
'default' => env('DB_CONNECTION', 'mongodb'), //默認數據庫爲mongo connections 追加: 'mongodb' => [ //MongoDB 'driver' => 'mongodb', 'host' => '10.2.20.46', 'port' => 10001, 'username' => '', 'password' => '', 'database' => 'userbehavior', //demodb 'options' => [] ],
三、Modelmongodb
*使用mongodb的Model
中的collection
至關於MySQL中的表名設置:數據庫
protected $collection = 'table';
主鍵是默認的_id
app
*不使用mongodb的Model
添加composer
protected $connection = 'mysql';
或者修改/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
中的
//protected $connection; protected $connection = 'mysql';
四、Query Builder
mongodb的操做能夠使用laravel封裝好的查詢構造器等等 須要注意的是: DB:table(''); => DB:collection('') 詳見:https://github.com/jenssegers/laravel-mongodb/tree/v3.1.0-alpha