首页 > 解决方案 > laravel 与自定义查询的多对多关系

问题描述

我有两个具有多对多关系的表产品和道具。每个产品都有一些道具,每个道具都适用于某些产品。在搜索过滤器中,我只需要获取具有选定道具的产品。我怎样才能做到这一点?

Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    ....
    $table->timestamps();
});
Schema::create('props', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    ....
    $table->timestamps();
});

Schema::create('product_prop', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('product_id');
    $table->unsignedBigInteger('prop_id');
    $table->timestamps();
    $table->foreign('product_id')
          ->references('id')
          ->on('products')
          ->onDelete('cascade');
    $table->foreign('prop_id')
          ->references('id')
          ->on('props')
          ->onDelete('cascade');
});

products: 
id=> 1, title=> p1
id=> 2, title=> p2
id=> 3, title=> p3
id=> 4, title=> p4
id=> 5, title=> p5
props:
id=> 1, title=> p1
id=> 2, title=> p2
id=> 3, title=> p3
id=> 4, title=> p4
id=> 5, title=> p5

product 1 has prop 1 and 2
product 3 has prop 2 and 4
product 4 has prop 5

$selectedProps = [1,5] 

所以我需要得到产品1和4!但我不知道如何获得。

标签: laravel

解决方案


试试下面的代码,在此之前我假设你有Products模型和Props模型。

在你的Product模型中

public function props(){
   return $this->hasMany('Props');
}

在你的Props模型中

public function product(){
   return $this->belongsToMany('Product');
}

现在构建器获取所选道具的产品。

Props::with('product')->whereHas('product')->where('id', $selectedPropsId)->get();

注意:我的回答是基于您的问题,抱歉,您的问题没有更多信息。


推荐阅读