那么,如果这是你想要的,根据你的评论,你可以这样做。
首先,您需要在您的productucs和您的类别之间建立适当的关系。
在您产品型号:
public function category()
{
return $this->belongsToMany('App\Category');
}
在您类别型号:
public function product()
{
return $this->belongsToMany('App\Product');
}
接下来,你需要创造一个适当的透视表,以这两个模型连接。因此,为此创建一个迁移。
php artisan make:migration create_category_product_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryProductTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->unsignedInteger('product_id');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('category_product');
}
}
现在你可以做一个小功能和访问它,它通过控制器发送到您的观点:
public function getRelatedProducts($product){
$related_category_ids = $product->category()->pluck('categories.id');
return $relatedProducts = Product::whereHas('category', function ($q) use($related_category_ids) {
$q->whereIn('category_id', $related_category_ids);
})
->where('id', '<>', $product->id)
->take(4)
->inRandomOrder()
->get();
}
对不起,你为什么不使用多对多关系? –
我正在使用过滤器。一种产品属于多种类别。 – kunal
是的,您拥有属于多个类别的产品,而且您的类别有许多产品。如果你设置了它们之间的多对多关系,你可以轻松地进行任何类型的过滤。 –