Laravel найти записи через промежуточную таблицу - PullRequest
0 голосов
/ 22 января 2020

У меня есть 3 модели:

  • Пользователь
  • Компания
  • Запрос

Пользователь может владеть несколькими компаниями, компания может принадлежать только одному пользователю. Запрос может принадлежать многим компаниям, а компания может иметь много запросов.

Миграции выглядят следующим образом:

Миграция пользователя

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('contact_number');
            $table->longText('address')->nullable();
            $table->integer('postal_code');
            $table->string('activation_token')->nullable();
            $table->boolean('active')->default(false);
            $table->enum('type', ['Admin', 'End User', 'Service Provider', 'Broker']);
            $table->string('password')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });

Миграция компании

Schema::create('companies', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('service_provider_id')->nullable();
            $table->unsignedInteger('broker_id');
            $table->string('name');
            $table->string('email')->unique()->nullable();
            $table->string('contact_number');
            $table->longText('address')->nullable();
            $table->integer('postal_code');
            $table->enum('status', ['Confirmed', 'Declined', 'New'])->default('New');
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::table('companies', function (Blueprint $table) {
            $table->foreign('service_provider_id')->references('id')->on('users');
            $table->foreign('broker_id')->references('id')->on('users');
        });

Миграция запросов

Schema::create('enquiries', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('end_user_id');
            $table->unsignedInteger('category_id');
            $table->string('title');
            $table->longText('description');
            $table->integer('radius');
            $table->enum('status', ['New', 'In Progress', 'Complete'])->default('New');
            $table->timestamps();
        });

        Schema::table('enquiries', function (Blueprint $table) {
            $table->foreign('end_user_id')->references('id')->on('users');
            $table->foreign('category_id')->references('id')->on('categories');
        });

Миграция запроса компании

Schema::create('company_enquiry', function (Blueprint $table) {
            $table->integer('company_id')->unsigned()->index();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->integer('enquiry_id')->unsigned()->index();
            $table->foreign('enquiry_id')->references('id')->on('enquiries')->onDelete('cascade');
            $table->primary(['company_id', 'enquiry_id']);
        });

Я установил различные отношения в их соответствующих моделях.

То, чего я пытаюсь добиться, - это запросить базу данных, чтобы получать только те запросы, которые принадлежат пользователю через компанию.

Как мне этого добиться?

Ответы [ 2 ]

0 голосов
/ 22 января 2020

Вы могли бы сделать это с более коротким кодом.

$enquiries = Enquiries::whereHas('companies.user', function($query) use($user_id){
       $query->where('id', $user_id);
 })->get();
0 голосов
/ 22 января 2020

Примерно так (добавить реальную модель, имена отношений и столбцы):

$enquiries = Enquiries::whereHas(['companies' => function($query){
                $query->whereHas(['user' => function($query){
                     $query->where('id', $user_id);
                }]);
            })
            ->get();
...