Laravel-从多对多关系中获取数据

时间:2018-12-24 12:32:31

标签: php css html5 laravel-5

我有很多关系

public function products()
{

    return $this->belongsToMany(Product::class); // relation between books and categories

}

public function parts()
{

    return $this->belongsToMany(Part::class); // relation between books and categories

}

我的迁移:

public function up()
{
    Schema::create('products', function (Blueprint $table) {

        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('link')->default('anohe.com');
        $table->string('pname')->default('product');
        $table->timestamps();
        $table->string('description',3000)->nullable();
        $table->string('smalldescription',500)->nullable();

    });
}

public function up()
{
    Schema::create('parts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('part_product', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('product_id');
        $table->unsignedInteger('part_id');
        $table->timestamps();

        $table
            ->foreign('product_id')
            ->references('id')
            ->on('products')
            ->onDelete('cascade');

        $table
            ->foreign('part_id')
            ->references('id')
            ->on('parts')
            ->onDelete('cascade');

    });

}

如何获得具有特殊part_id的产品?

1 个答案:

答案 0 :(得分:1)

如果您的关系正确,那应该可以:

$specialPartIds = [1];

$products = Product::whereHas('parts', function ($query) use ($specialPartIds) {
    $query->whereIn('id', $specialPartIds);
})->get();

dd($products->toArray());