Отображение записей на основе таблицы отношений в Laravel - PullRequest
0 голосов
/ 09 июля 2020

Я начинающий веб-разработчик. Я делаю свой проект в Laravel 7.

У меня есть этот код:

Миграция:

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 155);
            $table->string('title', 155);
            $table->string('description', 155)->nullable();
            $table->string('keywords', 155)->nullable();
            $table->longText('content')->nullable();
            $table->string('delivery_time', 155)->nullable();
            $table->string('small_description', 155)->nullable();
            $table->smallInteger('vat_id')->unsigned()->default(1);
            $table->foreign('vat_id')->references('id')->on('vat');
            $table->bigInteger('category_id')->unsigned()->default(0);
            //$table->foreign('category_id')->references('id')->on('categories');
            $table->char('enable', 1)->default(0);
            $table->char('product_type', 1)->default(0);
            $table->string('slug', 160)->nullable();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });



Schema::create('selected_product_features', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->bigInteger('feature_id')->unsigned();
            $table->foreign('feature_id')->references('id')->on('product_features')->onDelete('cascade');
            $table->string('key', 50);
            $table->text('description')->nullable();;
            $table->timestamps();
        });

Мне нужно показать все продукты в форме selected_product_features key = " -2 "и description = 1.

Как это сделать?

Ответы [ 2 ]

1 голос
/ 09 июля 2020

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

public function productSelectedFeature()
{
    return $this->hasMany('App\Models\SelectedProductFeatures', 'product_id', 'id');
}

, а затем вы можете написать свой запрос в контроллере как

$products = Products::with('productSelectedFeature')->where('description', 1)
            ->whereHas('productSelectedFeature', function($q) {
                $q->where('key', "form-2");
            });
0 голосов
/ 09 июля 2020

Я бы начал с красноречивой документации, чтобы получить информацию о том, как таблицы базы данных доступны в вашем коде. См. https://laravel.com/docs/7.x/eloquent, чтобы начать работу с красноречивым.

Чтобы начать работу, приведенный ниже (псевдокод) должен быть примером вашей ситуации. (1): выберите правильные функции продукта (2): получите коллекцию совпадающих функций (3): сопоставьте функцию с продуктом

$flights = App\SelectedProductFeatures::where('key', 'form-2')
    ->where('description' 1) // (1)
    ->get() // (2)
    ->map(function($feature) { return $feature->product; }); // (3)

...