gpt4 book ai didi

php - 数据库查询: Select row where and where

转载 作者:行者123 更新时间:2023-11-29 10:47:40 25 4
gpt4 key购买 nike

我想创建一个搜索栏,但将结果限制为共享同一家公司的用户。这个功能运行良好:

public function search(Request $request) {
if ($user = Sentinel::check()) {
$users = User
::where('first_name', 'like', '%' . $request->text . '%')
->orWhere('last_name', 'like', '%' . $request->text . '%')
->limit(2)
->get()
->map(function ($item) {
$item['url'] = route('user.single', ['id' => $item->id]);
$item['title'] = $item['first_name'] . ' ' . $item['last_name'];
$item['type'] = 'User';
return $item;
})
->toArray();
}
}

但我想添加条件:

->andWhere ('companies_id', 1)

最佳答案

您可以简单地添加where子句

public function search(Request $request) {
if ($user = Sentinel::check()) {
$users = User
::where('first_name', 'like', '%' . $request->text . '%')
->where('companies_id', 1)
->orWhere('last_name', 'like', '%' . $request->text . '%')
->limit(2)
->get()
->map(function ($item) {
$item['url'] = route('user.single', ['id' => $item->id]);
$item['title'] = $item['first_name'] . ' ' . $item['last_name'];
$item['type'] = 'User';
return $item;
})
->toArray();
}
}

这将导致此查询

WHERE `firstname` LIKE '%?%'
AND `company_id` = 1
OR `lastname` LIKE '%?%'

但我认为应该是

WHERE `company_id` = 1
AND (
`firstname` LIKE '%?%'
OR `lastname` LIKE '%?%'
)

所以这些答案应该是正确的:https://stackoverflow.com/a/44281362/6193316

关于php - 数据库查询: Select row where and where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com