Laravel条件查询 [英] Laravel conditional query
本文介绍了Laravel条件查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个功能,我尝试在两列中搜索匹配的id,但是即使实际上没有结果,它总是返回 true
.
I have function where I try to search in 2 columns for matched id but in all times it return true
even where there is actually no result.
我想搜索用户以前的关系,但不确定如何使这种逻辑发生.
I want to search for users previous relations but not sure how to make this logic happen.
- 我的表有2列
from_id
和to_id
(均会获取用户ID) - 我正在向后端发送2个ID(一个作为输入,另一个在请求中标头)
- 我想说的是:其中输入的
id
是from_id
,标头ID是to_id
,或其中输入id
是to_id
和标头id
是from_id
返回结果,否则显然为null.
- My table has 2 columns
from_id
andto_id
(both will get users ids) - I am sending 2 ids to back-end (one as input, another one in request header)
- I want to say: where input
id
isfrom_id
and header id isto_id
, ORwhere inputid
isto_id
and headerid
isfrom_id
return the result otherwise is null obviously.
代码
public function check(Request $request) { // always return true!
$user = $request->user();
$userInput = $request->input('receiverId');
$chat = PrivateChat::where(function ($query) use ($user) {
$query->where('from_id', $user->id)->orWhere('to_id', $user->id);
})->orWhere(function ($query) use ($userInput) {
$query->where('from_id', $userInput)->orWhere('to_id', $userInput);
})->first();
$receiver = User::where('id', $request->input('receiverId'))->first();
if($chat) {
return response()->json([
'data' => new PrivateChatResource($chat),
'exist' => true,
'receiver' => new UserResource($receiver),
'message' => 'Chat data retrieved successfully.'
]);
} else {
return response()->json([
'exist' => false,
'receiver' => new UserResource($receiver),
'message' => 'Chat data retrieved successfully.'
]);
}
}
注意:这是我的旧问题的后续操作
知道是什么问题吗?
基于 Giacomo M
的评论,我认为这应该是最终代码
Based on Giacomo M
comment i think this should be the final code
$chat = PrivateChat::where(function ($query) use ($user, $userInput) {
$query
->where('from_id', $user->id)
->where('to_id', $userInput);
})->orWhere(function ($query) use ($user, $userInput) {
$query
->where('from_id', $userInput)
->where('to_id', $user->id);
})->first();
有意义吗?
推荐答案
您也可以在子查询中使用 orWhere
,但是根据您的逻辑,您需要在子查询中使用AND.
You use orWhere
also in the subqueries, but according to your logic you need AND in the subqueries.
您的查询将变为:
$chat = PrivateChat::where(function ($query) use ($user) {
$query
->where('from_id', $user->id)
->where('to_id', $user->id); // where, NOT orWhere
})->orWhere(function ($query) use ($userInput) {
$query
->where('from_id', $userInput)
->where('to_id', $userInput); // where, NOT orWhere
})->first();
这篇关于Laravel条件查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文