1. 程式人生 > >Laravel中使用mongodb(安裝及專案內使用)

Laravel中使用mongodb(安裝及專案內使用)

1、安裝

(1)先安裝php7的mongodb擴充套件

安裝好對應版本之後,檢視php-info()如下表示安裝成功

(2)確定已經安裝好php的mongodb的擴充套件之後

進入專案的根目錄,命令列執行

composer require jenssegers/mongodb

(3)在config/app.php下注冊服務

'providers'  中加入
Jenssegers\Mongodb\MongodbServiceProvider::class,
'aliases' 中加入
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
'Mongo'     => Jenssegers\Mongodb\MongodbServiceProvider::class,

2、配置

在config/database.php中配置資料庫

'connections' 中加入
'mongodb' => array(         //MongoDB
    'driver'   => 'mongodb',
    'host'     => '1xx.1xx.1xx.1x',  //資料庫伺服器的ip
    'port'     => 27017,            //資料庫伺服器上mongodb服務對應的埠
    'database' => 'task_manager',  //資料庫名稱
    'username' => 'user',
    'password' => 'xxx',
    'options' => array(
        'database' => 'task_manager' // 要使用的資料庫
    )

),

3、專案中的具體使用

方法一:

(1)在app下新建一個Mongodb.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/27 0027
 * Time: 上午 11:19
 */

namespace App;


use DB;

class Mongodb
{
    public static function connectionMongodb($tables)
    {
        return $users = DB::connection('mongodb')->collection($tables);
    }
}

(2)在controller中使用

增:

$connection = Mongodb::connectionMongodb('xxx表名');
$result= $connection ->insert($data);

刪:

$connection = Mongodb::connectionMongodb('xxx表名');
$result= $connection ->where('id', $id)->delete();

改:

$connection = Mongodb::connectionMongodb('xxx表名');
$result= $connection ->where('id',$id)->update($data);

查:

$connection = Mongodb::connectionMongodb('xxx表名');

//不分頁 
$result= $connection ->get();
如果用了軟刪除,此處要加上$result=$connection->whereNull('deleted_at')->get();
//分頁
可以預設分頁數,或者根據傳入data的指定頁數進行分頁
if(isset($data['pageSize'])){
    $pageSize = $data['pageSize'];
}else{
    $pageSize=6;
}
$results=$connection->paginate($pageSize);
$connection = Mongodb::connectionMongodb('xxx表名');
$result= $connection ->where('id',$id)->get();

方法二:

(1)在要操作的資料表對應的實體類中引用mongodb的Model

<?php

namespace App;

use Emadadly\LaravelUuid\Uuids;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;


class ExampleModel extends Model
{
    //
    use Uuids;

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    use SoftDeletes;

    protected $connection = 'mongodb';
    protected $collection = 'xxx表名';     //表名
    protected $primaryKey = 'id';    //設定主鍵
    protected $fillable = [ 'id','title', 'type','xx'];  //設定欄位白名單


    /**
     * 需要被轉換成日期的屬性。
     *
     * @var array
     */

    protected $dates = ['deleted_at'];

}

(2)在controller中使用

$result=ExampleModel ::create($data);

$result= ExampleModel ::where('id', $id)->delete();

$result= ExampleModel ::where('id',$id)->update($data);

$result= ExampleModel ::all();
$result= ExampleModel ::where('id',$id)->get();​​​​​​​