简体   繁体   English

Laravel whereIn 没有给出想要的结果

[英]Laravel whereIn not giving desired result

I have the following two tables:我有以下两个表:

unotes    unote_unit
======    ==========
id        unote_id
notes     unit_id

I am trying to retrieve unotes row whose related unit_id columns exactly match an input array.我正在尝试检索相关unit_id列与输入数组完全匹配的unotes行。

So, I run following query:所以,我运行以下查询:

$unote = UNote::whereHas('units', function ($query) use ($request) {
        $query->whereIn('units.id', $request->unit_lists);
    })
    ->withCount('units')
    ->having('units_count', '=', $u_list_count)
    ->get()
    ->pluck("id");

But, the problem with the above query is that even if it has just a single matching unit_id , it retrieves the data.但是,上述查询的问题在于,即使它只有一个匹配的unit_id ,它unit_id检索数据。 For example I have following datasets:例如我有以下数据集:

unotes //with related unit_id
========
id = 3 //49865, 49866, 49867
id = 4  //49865, 49866

With above mentioned code, if I pass [49866,55555] , it should return nothing but it returns ids 3 and 4, which contain one match but not all.使用上面提到的代码,如果我通过[49866,55555] ,它应该返回什么,但它返回 ids 3 和 4,其中包含一个匹配项但不是全部。

I have found similar question on Laracasts as well but running the query returns Cardinality violation: 1241 Operand should contain 2 column(s) :我在Laracasts上也发现了类似的问题,但运行查询会返回Cardinality violation: 1241 Operand should contain 2 column(s) conflict Cardinality violation: 1241 Operand should contain 2 column(s)

$unote = UNote::with('units')
    ->whereHas('units', function ($query) use ($request) {
        $query->selectRaw("count(distinct id)")->whereIn('id', $request->unit_lists);
    }, '=', $u_list_count)
    ->get()
    ->pluck("id");

I also found a similar question here , but seems it is too expensive.我也在这里找到了一个类似的问题,但似乎太贵了。

Here is the dummy SQL to get started: http://sqlfiddle.com/#!9/c3d1f7/1这是开始使用的虚拟 SQL: http : //sqlfiddle.com/#!9/c3d1f7/1

Because whereHas just adds a WHERE EXISTS clause to the query with your specified filters, a whereIn will indeed return true for any matches.因为whereHas只是使用您指定的过滤器向查询添加了WHERE EXISTS子句,所以whereIn确实会为任何匹配返回 true。 One thing you could try is running a raw subquery to get a list of device IDs and compare it.您可以尝试的一件事是运行原始子查询以获取设备 ID 列表并进行比较。

$search_ids = [49866, 49865];
sort($search_ids);
$search_ids = implode(",", $search_ids);

Unote::select("id")
    ->whereRaw(
        "(SELECT GROUP_CONCAT(unit_id ORDER BY unit_id) FROM unote_unit WHERE unote_id = unotes.id) = ?",
        [$search_ids]
    )
    ->get()
    ->pluck("id");

Note, if you have soft deletes enabled you will also want to filter out soft deleted items in the subquery.请注意,如果您启用了软删除,您还需要过滤掉子查询中的软删除项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM