根据 Laravel 中的关系 table 显示记录

Displaying records based on a relationship table in Laravel

我是初学者 Web 开发人员。我在 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 = "form-2" 和 description = 1 中的所有产品。

我怎样才能做到?

我将从 eloquent 文档开始,以获取有关如何在您的代码中使用数据库表的信息。请参阅 https://laravel.com/docs/7.x/eloquent 以开始使用 eloquent。

为了让您快速入门,下面的(伪)代码应该是您所处情况的示例。 (1): Select 正确的产品特性 (2):获取匹配特征的集合 (3): 将特征映射到产品

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

首先你必须在产品模态

中建立产品table与所选产品功能table的关系
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");
            });