我想在Laravel中分页我的选择查询

时间:2019-07-07 20:25:47

标签: laravel laravel-5 eloquent

在Laravel中对select使用分页时,查询出现问题。但是,我找到了一些Laravel Eloquent代码,但问题是它也不起作用。谁能帮助我解决这个问题?

public function categoryall($urlid)
{
    // Old query
    // $procat = DB::select('select * from products where category_id in 
    // (select id from categories where parent_id = ?)', [$urlid]);

    $procat = Product::whereIn('category_id', function ($query) {
        $query->select('id')
            ->from(with(new Category)->getTable())
            ->where('parent_id', [$urlid]);
    })->paginate(5);

    return view('products.category')->with(compact('procat'));
}

2 个答案:

答案 0 :(得分:3)

您需要像这样function ($query) use ($urlid)where('urlid',$urlid) 如果需要,whereIn将其作为数组

答案 1 :(得分:1)

由于类别和产品表之间的关系是ManyMany,因此建立一个数据透视表category_product像这样:

    Schema::create('category_product', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();
        $table->bigInteger('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->bigInteger('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
    });

然后,在3个表上设置一些关系和数据,并使用以下功能进行分页:

public function categoryall($urlid)
{
    $category_ids = Category::where('parent_id',$urlid)->pluck('id'); // = [1,2]
    $products = Product::whereHas('categories', function($query) use ($category_ids) {
        $query->whereIn('category_id', $category_ids);
    })->paginate(5);
    return $products;
}

问我是否需要!