序言:
项目前期使用mysql数据库,后期数据量增大,需要将mysql部分表迁移至mongodb,需要对应修改该表所对应的关联关系。
使用mongodb模块:jenssegers/laravel-mongodb
GitHub地址:jenssegers/laravel-mongodb的Github链接
mongodb模型引入jenssegers/laravel-mongodb,并重写boot方法,并设定链接方式和链接集合:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; protected $connection = 'mongodb'; //链接方式 protected $collection = 'list'; //链接集合 重写boot方法: protected static function boot() { static::saving(function(Eloquent $model){ unset($model->user_name); }); parent::boot(); }
mysql模型需要设置链接类型、引入HybridRelations,如果不设置会出现connection链接错误的问题:
use Jenssegers\Mongodb\Eloquent\HybridRelations; //引入HybridRelations use HybridRelations; //所有与mongodb有关联的模型 都需要引入HybridRelations protected $connection = 'mysql';
mysql模型切换到mongodb模型,需确定主键id的设定,经过我测试,需要设定mongodb的_id字段为主键,默认不设置就可以了。
如果以前在mysql使用belongsTo模型进行关联的时,切换到mongodb,需要进行修改。
实例:mongodb模型(Dynamic) 待关联模型(User)如果在grid,laravel-admin 使用原有的关联关系在display默认链接将无法获取到数据,需要这么做:
$grid->model()->with('user');
从mysql模型更换到mongodb模型有关的查询,也需要对应更改查询方式
例如:Dynamic::find($id) 需要改为: Dynamic::where('id',$id);
在上述情况下,find将无法查询到数据,where却可以查询到,特性是引入mongodb需要使用Eloquent 查询,另外可以使用原生写法:
DB::collection('books')->where('name', 'Hunger Games')->first();
另外,原本与mysql模型关联的id,切换到了mongodb的_id,如果与其他客户端有冲突,需要在
关联表内进行mongodb的_id的存储,另外操作grid和form都以_id为主键,操作完之后,需要将
mysql原本的id与mongodb的_id进行对应,避免出现与其他客户端的冲突。多对多关联的方法,需要在被关联的表内创建存储mongodb的_id的字段,来与这个字段进行关联。