【问题标题】:Laravel whereIn not proper working with whereHasLaravel whereIn 不能正确使用 whereHas
【发布时间】:2021-07-25 21:24:06
【问题描述】:

我制作产品列表和过滤页面。所以我需要在 laravel 中进行动态查询。但是当我尝试 whereInwhereHas 时,在选择结果中缺少一些产品。我的代码如下。目前我有 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


【解决方案1】:

子查询应该是

$query->whereIn('id', $keys);

但你可以跳过所有这些,然后做

$input = $request->all();
$keys = [1, 2, 3];
Product::whereIn('main_category_id', $keys)->where(['price >' => $input['min'], 'price <' => $input['max']])->with(['getMainCategory'])->get();

另外,按照@JohnLobo 的建议,检查docs 中的foreign_key 和local_key 顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2019-01-22
    • 1970-01-01
    • 2014-05-10
    • 2023-03-07
    • 2021-06-10
    • 2017-09-21
    相关资源
    最近更新 更多