如何使用regexp

时间:2017-09-23 05:37:33

标签: php mysql laravel laravel-5.2

我正面临着问题。我想找到属于当前产品(category_ids)的产品。我在产品详细信息页面。这是我的表结构: - enter image description here

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

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

以上查询显示空结果。请帮我解决一下。我正在使用laravel 5.2

1 个答案:

答案 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();
}