首页 > 解决方案 > Laravel 雄辩的构建查询

问题描述

我想使用 Laravel Eloquent 结构编写一个查询。我想在输入最小值和最大值后查询这些值。我有一个产品表。带有折扣 (%) 和价格的列产品表。我想根据产品的折扣值获得最小值和最大值。

我希望这是基于包括折扣在内的查询。

$products->where('price', '<=', $max)
  ->where('price', '>=', $min)
  ->orderByDesc('id')
  ->paginate(9);

产品迁移:

Schema::create('products', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('upper_category_id')->index();
  $table->unsignedBigInteger('category_id')->index();
  $table->unsignedBigInteger('user_id')->index();
  $table->string('name');
  $table->longText('text');
  $table->float('price')->index();
  $table->integer('stock');
  $table->float('discount');
  $table->timestamps();
});

非常感谢您提前。

标签: phplaraveleloquent

解决方案


如果我正确理解了您的问题,您可以尝试这样做:

$products->where(DB::raw('price - price * discount'), '<=', $max)
  ->where(DB::raw('price - price * discount'), '>=', $min)
  ->orderByDesc('id')
  ->paginate(9);

https://laravel.com/docs/5.8/queries#raw-expressions


推荐阅读