【发布时间】:2021-07-25 21:24:06
【问题描述】:
我制作产品列表和过滤页面。所以我需要在 laravel 中进行动态查询。但是当我尝试 whereIn 和 whereHas 时,在选择结果中缺少一些产品。我的代码如下。目前我有 3 个主要类别,她的 id 是 1,2,3。
控制器
$input = $request->all();
$products = Product::with('getMainCategory')->where('price', '>', $input['min'])->where('price', '<', $input['max']);
$keys = [1, 2, 3];
$products->whereHas('getMainCategory', function ($query) use ($keys) {
$query->whereIn('main_category_id', $keys);
});
$products = $products->get();
型号
<?php
namespace App\Models\ProductModel;
use App\Models\MainCategoryModel\MainCategory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $guarded = [];
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
public function getMainCategory() {
return $this->belongsTo('App\Models\MainCategoryModel\MainCategory', 'id', 'main_category_id');
}
}
【问题讨论】:
-
看起来问题出在关系键上 public function getMainCategory() { return $this->belongsTo('App\Models\MainCategoryModel\MainCategory', 'main_category_id', 'id'); }
标签: php laravel codeigniter