# 在项目中使用
# 安装 composer 包
官方有提供各类语言的驱动,在 PHP 语言类的项目中,官方也有提供像 laravel , symfony , yii 等框架的使用方法。https://www.mongodb.com/docs/languages/php/ (opens new window)
# 安装扩展包,当然要注意版本,没必要和我版本一致
composer require mongodb/laravel-mongodb
注意一下:安装包的主版本3和4版本的服务提供者类名不一致。
# 3版本
Jenssegers\Mongodb\MongodbServiceProvider::class,
# 4版本
MongoDB\Laravel\MongoDBServiceProvider::class,
# 配置 databse.php 文件
connections => [
.
.
.
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_DATABASE_URL'),
'host' => env('MONGODB_HOST', '127.0.0.1'),
'port' => env('MONGODB_PORT', '27017'),
'database' => env('MONGODB_DATABASE', 'forge'),
'username' => env('MONGODB_USERNAME', 'homestead'),
'password' => env('MONGODB_PASSWORD', 'secret'),
'charset' => 'utf8',
'prefix' => '',
'options' => [],
'driverOptions' => [],
],
],
# CURD
1、创建一个 Movie 模型
php artisan make:model Movie -cr
2、编辑模型
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
class Movie extends Model
{
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* @var array<string>
*/
protected $fillable = ['cover','director'];
}
3、数据的CURD
<?php
namespace App\Http\Controllers;
use App\Models\Movie;
use Illuminate\Http\Request;
class MovieController extends Controller
{
public function store(Request $request)
{
Movie::query()->create([
'cover' => 'http://wximg.me-tn.com/prefer/goutong.jpg',
'director' => '李淙翰',
]);
}
public function show()
{
return Movie::all();
}
public function update()
{
Movie::query()->where('name','李淙翰')->update(['cover'=>'http://wximg.me-tn.com/prefer/guanxi.jpg']);
}
public function destroy()
{
Movie::query()->where('name','李淙翰')->delete();
}
}