首页 文章

Laravel - Mongodb [jenssegers / laravel-mongodb] - Schema Builder

提问于
浏览
1

我有一个mongodb的web应用程序,使用jenssegers包 .

由于我使用的是mongodb,我是否需要创建任何迁移表? Jenssegers数据库驱动也有(有限)schema builder support

Schema::create('users', function($collection)
{
    $collection->index('name');

    $collection->unique('email');
});

我找到了两个不同的"answers" . 这家伙正在使用the schema builder

enter image description here

而Mulkave回答:

Q :"When i run the comman " php artisan migrate " then i am getting following error where as migration table is created into mongodb database:"

A :“_ You might have misinterpreted the purpose of MongoDB being a document database, you do not need to have migrations in document-based databases and this is what they're good a . 他们有动态模式,所以你必须收紧应用程序的业务逻辑,以确保模型按预期保存 . ”


那么,我需要迁移表吗?谢谢!

1 回答

  • 1

    我知道这有点晚了,但我想我会在这里输入一些代码 . 我喜欢索引模型有两个原因:

    • 我可以像接口一样使用它,即我被迫输入此信息,因为它不是一个要求's part of what the model requires. This ensures that I have a clean dataset. This is just preference, it' .

    • 索引搜索比不索引时更快 . I haven't done enough research into this to figure out if this is the case with jenssegers library . 但是对我来说,如果你使用模式来设置集合并将其设置为索引这些字段,那么在搜索此集合中的记录时会更快 . 您也可以从Mongo端手动设置它,但我喜欢您可以使用此Eloquent扩展来完成此操作 .

    所以对于读这篇文章的人来说,如果我用这个未经证实的论证说服你,那么你发现它很容易设置收藏但不容易丢弃它 . 如果要进行完整迁移( be aware that you'll lose all of your data when you do this ),则可以使用以下代码:

    <?php
    
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateYourCollectionTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::connection('mongodb')->create('collection_name', function ($collection) {
                $collection->index('field_1');
                $collection->index('field_2');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            DB::connection('mongodb')->drop(['collection_name']);
        }
    }
    

相关问题