laravel-mongodb与Eloquent深度整合:ORM特性全解析
【免费下载链接】laravel-mongodb 项目地址: https://gitcode.com/gh_mirrors/lar/laravel-mongodb
核心架构概览
laravel-mongodb实现了MongoDB与Laravel Eloquent ORM(对象关系映射)的深度整合,使开发者能够使用熟悉的Laravel模型语法操作MongoDB文档数据库。项目核心模型类MongoDB\Laravel\Eloquent\Model继承自Laravel基础模型,通过DocumentModel trait扩展MongoDB特有功能,实现了文档与对象的无缝映射。
官方文档:docs/eloquent-models.txt
核心模型源码:src/Eloquent/Model.php
模型定义与基础操作
基本模型定义
创建MongoDB模型只需继承MongoDB\Laravel\Eloquent\Model,默认使用类名的蛇形复数形式作为集合名(如Planet模型对应planets集合):
<?php
namespace App\Models;
use MongoDB\Laravel\Eloquent\Model;
class Planet extends Model
{
}
模型示例:docs/includes/eloquent-models/Planet.php
核心特性定制
通过重写模型属性实现功能定制:
- 集合名定制:指定
$collection属性 - 主键定制:默认使用
_id字段,可通过$primaryKey修改 - 软删除:引入
SoftDeletestrait实现文档标记删除 - 数据类型转换:通过
$casts属性定义字段类型转换规则
// 软删除示例
use MongoDB\Laravel\Eloquent\SoftDeletes;
class Planet extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
高级关系映射
嵌入式关系
MongoDB特有的嵌入式关系允许将子文档直接存储在父文档中,通过embedsOne和embedsMany方法定义:
use MongoDB\Laravel\Relations\EmbedsMany;
class SpaceShip extends Model
{
public function cargo(): EmbedsMany
{
return $this->embedsMany(Cargo::class);
}
}
嵌入式关系示例:docs/includes/eloquent-models/relationships/embeds/SpaceShip.php
关联关系类型
支持多种关系类型,包括:
- 一对一:
hasOne/belongsTo - 一对多:
hasMany/belongsTo - 多对多:
belongsToMany - 嵌入式:
embedsOne/embedsMany
关系定义文档:docs/eloquent-models/relationships.txt
schema构建与索引管理
迁移文件示例
使用MongoDB专用的Blueprint类创建集合和索引:
use MongoDB\Laravel\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::create('planets', function (Blueprint $collection) {
$collection->sparse('rings'); // 稀疏索引
$collection->expire('last_visible_dt', 86400); // 过期索引(24小时)
});
迁移示例:docs/includes/schema-builder/planets_migration.php
索引类型支持
提供丰富的索引创建方法:
- 地理空间索引:
geospatial - 全文索引:
text - 复合索引:
index方法传入多字段数组 - 唯一索引:
unique
索引管理源码:src/Schema/Blueprint.php
数据操作与查询构建
基本CRUD操作
完全兼容Laravel Eloquent查询语法:
// 创建文档
$earth = Planet::create([
'name' => 'Earth',
'radius' => 6371,
'has_water' => true
]);
// 查询文档
$recentPlanets = Planet::where('discovery_dt', '>', now()->subYears(5))
->orderBy('distance_from_sun')
->get();
// 更新文档
$earth->update(['population' => 7.9e9]);
// 删除文档(软删除)
$earth->delete();
高级查询特性
支持MongoDB特有查询操作:
- 数组查询:
where('tags', 'all', ['rocky', 'terrestrial']) - 地理空间查询:
whereNear('location', [$longitude, $latitude], $maxDistance) - 聚合管道:通过
raw()方法执行原生聚合操作
查询构建器源码:src/Query/Builder.php
实战应用场景
认证系统集成
通过扩展MongoDB\Laravel\Auth\User实现MongoDB认证:
use MongoDB\Laravel\Auth\User as MongoUser;
class User extends MongoUser
{
// 自定义用户模型
}
数据生命周期管理
使用MassPrunable trait实现文档自动清理:
use MongoDB\Laravel\Eloquent\MassPrunable;
class LogEntry extends Model
{
use MassPrunable;
public function prunable()
{
return static::where('created_at', '<=', now()->subDays(30));
}
}
性能优化策略
- 索引优化:合理使用
index、unique、sparse等索引类型 - 查询优化:使用
select限制返回字段,避免*查询 - 批量操作:使用
insertMany、updateMany减少数据库交互 - 连接池配置:优化
config/database.php中的MongoDB连接参数
索引管理文档:docs/eloquent-models/schema-builder.txt
总结
laravel-mongodb通过精巧的架构设计,将MongoDB的文档特性与Laravel的优雅语法完美融合,既保留了MongoDB的灵活性,又提供了Eloquent ORM的开发便利性。核心优势包括:
- 零学习成本:Laravel开发者可直接使用熟悉的模型语法
- 完整功能集:支持关系映射、软删除、数据验证等全部ORM特性
- 性能优化:针对MongoDB特性优化的查询构建器和索引管理
- 生态集成:无缝对接Laravel认证、队列、缓存等核心组件
【免费下载链接】laravel-mongodb 项目地址: https://gitcode.com/gh_mirrors/lar/laravel-mongodb
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



