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

标签 php mysql database laravel

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

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/

相关文章:

php - JOIN 查询只返回第一行

php - 无法登录 localhost/phpmyadmin

php - dropzone.js 发送空 $_FILES

php - 在 where 子句中选择具有长比较的记录的最佳技术是什么

database - 如何将数据从 CRM 4.0 数据库传输到另一个 CRM 4.0 数据库?

php - Doctrine2 引发 preFlush 的次数过多(?)

php - 用户隐藏个人信息的数据库结构

php - 在 PHP 中上传多个文件

php - 在 WooCommerce 中向电子邮件主题添加自定义占位符

php - 使用 Ajax 或 JavaScript 选择下拉列表选项后在同一页面上执行 PHP 脚本