首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Laravel Moloquent创建索引

用Laravel Moloquent创建索引
EN

Stack Overflow用户
提问于 2018-05-18 07:08:22
回答 1查看 4.3K关注 0票数 0

我是MongoDB的新手。

我正在使用Jensegger/Laravel-MongoDB Moloquent特性来处理Mongo。

我试图用这个方法创建一个集合的索引:-

代码语言:javascript
复制
Schema::collection('events', function ($table) {
     $table->index(['location' => '2dsphere']);
});

然而,我的错误是:-

代码语言:javascript
复制
Class Jenssegers\Mongodb\Schema' not found

我也加了这两条:-

代码语言:javascript
复制
use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

我有一个控制器方法,如下所示:

代码语言:javascript
复制
public function fetchMongoTest(Request $request){
    $error = FALSE;
    $respond = array();
    $detail = array();
    $err_message = array();
    $err_validation = array();
    $api_code       = 2001; 
    try 
    {
        if ($request->isMethod('post')) 
        {
            $latitude = (float)$request->latitude;
            $longitude = (float)$request->longitude;
            $status     = 1;
            $mongoData = array();
            $monTestObj = new Mongotest;

            Schema::collection('events', function ($table) {
                $table->index(['location' => '2dsphere']);
            });

            $monTestObj->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0]];
            $monTestObj->save();



            $users = MongoTest::where('loc', 'near', [
                '$geometry' => [
                    'type' => 'Point',
                    'coordinates' => [
                        $longitude,
                        $latitude
                    ]
                ],
                '$maxDistance' => 10,
            ]);

            foreach($users as $u)
                {
                    print_r($u->name);
                }


        }
        else 
        {
            $status     = 0;
            $message    = Config::get('customConfig.api_messages.ENG.post_request_mandatory');
            $err_message[] = $message;
        }
    }
    catch(Exception $e) 
    {
        $status = 0; 
        echo $e->getMessage(); die;
        $message=Config::get('customConfig.api_messages.ENG.exception_error');
    }
    $response['status']         = $status;
    $response['message']        = $message;
    $response['details']        = $detail;
    $response['error']          = $err_message;
    $response['error_validation_key'] = $err_validation;
    $response['api_version']    = $this->api_version;
    $response['api_code']       = $api_code;

    $respond['fetch-activity-list-prime'] = $response;
    $jsonResult = json_encode($respond);    
    header('Content-Type: application/json; charset=utf-8');    
    echo $jsonResult ;      
    exit();
}

如何检查集合是否存在,如果不存在,如何创建新集合?

编辑:

这是我的MongoTest模型:-

代码语言:javascript
复制
<?php
namespace App\Http\Model;
//use Illuminate\Database\Eloquent\Model;
use Moloquent;
class MongoTest extends Moloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'test';
    //protected $collection = 'rh_country_help_text';
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-18 08:40:14

你好像从某个地方得到了部分答案。Schema应该从“大规模迁移”中获取,这是在应用程序中实际定义索引的推荐方法之一。

这个过程将是设置如下:

创建迁移

代码语言:javascript
复制
php artisan make:migration create_location_index

然后更改结构以添加用于创建和删除索引的updown

代码语言:javascript
复制
<?php

    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

    class CreateLocationIndex extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->index([ "loc" => "2dsphere" ]);
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
                $collection->dropIndex(['loc_2dsphere']);
            });
        }
    }

然后,您可以以在文件中详细说明的形式运行迁移。

如果您决定在迁移过程之外运行代码,那么获取MongoDB\Collection对象的备用句柄可以如下所示:

代码语言:javascript
复制
DB::collection('test')->raw(function($collection) {
  return $collection->createIndex([ 'loc' => '2dsphere' ])
}

不管您做什么,这段代码不属于控制器。创建索引的代码只需运行一次。通常情况下,您的数据库部署“只进行一次”,但是在每次启动应用程序时发出命令并不会造成真正的伤害,但是它肯定会对每个请求造成伤害。所以别把它放在那里。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50405662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档