2017-09-23 102 views
0

我正面临问题。我想查找属于当前产品(category_ids)的产品。我在产品详细信息页面。这里是我的表的结构: - enter image description here如何使用正则表达式在laravel中获取产品

现在看到我目前在浏览器中打开2产品和含有category_ids(4,2)现在我想获取具有我的情况下CATEGORY_ID 4或2中的所有产品我想要获取第三个产品,但它不工作..看到第三个产品有category_id(1,2,6),所以我想获取该记录...所以,如果在浏览器中打开第三个产品,我想获取2产品。 。希望你们在这里承担的是我的代码: -

$recomendedProducts = Product::with('product_image') 
        ->whereRaw("category_ids REGEXP '".$productDetail['category_ids']. "'") 
         ->where('id','!=',$productDetail['id']) 
        ->inRandomorder() 
         ->take(5) 
         ->get(); 

这上面的查询显示我空的结果。请帮我解决。我正在使用laravel 5.2

+0

对不起,你为什么不使用多对多关系? –

+0

我正在使用过滤器。一种产品属于多种类别。 – kunal

+0

是的,您拥有属于多个类别的产品,而且您的类别有许多产品。如果你设置了它们之间的多对多关系,你可以轻松地进行任何类型的过滤。 –

回答

0

那么,如果这是你想要的,根据你的评论,你可以这样做。

首先,您需要在您的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(); 
} 
相关问题