需求,載入禮物表中,租戶id=0 和租戶id=10 的資料,並排除 id =10,11,12
第一次寫法(這個寫法是錯誤的)
$whereOr=[
['tenant_id', '=', 0],
['gift_id', 'not in', [1,2,3]]
];
$where=[
['tenant_id', '=', 10],
['gift_id', 'not in', [1,2,3]],
]
ActivityVoteGiftModel::where($where)->whereOr($whereOr)->select();
//得到的sql
SELECT
tenant_id
FROM
`yjy_live_gift` ``
WHERE
`tenant_id` = 10
AND `id` NOT IN ( 11, 10, 9 )
OR `tenant_id` = 0
OR `id` NOT IN ( 11, 10, 9 )
ORDER BY
id DESC
LIMIT 0,10
查詢出來的結果 只要租戶id 等於0 或者 id 只要不等於 11,10,9 的資料就會查詢出來
正確的條件應該是
(`tenant_id` = 10 AND `id` NOT IN ( 11, 10, 9 ) )
or
(`tenant_id` = 0 and `id` NOT IN ( 11, 10, 9 ) )
第二次寫法
$whereOr=[
['tenant_id', '=', 0],
['gift_id', 'not in', [1,2,3]]
];
$where=[
['tenant_id', '=', 10],
['gift_id', 'not in', [1,2,3]],
]
ActivityVoteGiftModel::whereOr([$whereOr,$where])->select();
//得到的sql
SELECT
tenant_id
FROM
`yjy_live_gift` ``
WHERE
(`tenant_id` = 10 AND `id` NOT IN ( 11, 10, 9 ) )
or
(`tenant_id` = 0 and `id` NOT IN ( 11, 10, 9 ) )
ORDER BY
id DESC
LIMIT 0,10
thinkphp 解決方案地址 https://www.kancloud.cn/manual/thinkphp5_1...
第三次寫 使用in查詢
$where=[
['tenant_id', 'in',[10,0]],
['gift_id', 'not in', [1,2,3]],
]
ActivityVoteGiftModel::where($where)->select();
再次仔細文件發現,可以同一欄位多個查詢條件可以使用區間查詢 https://www.kancloud.cn/manual/thinkphp5_1...