使用 Laravel Eloquent / MySQL 比较多个数据库行值

Posted

技术标签:

【中文标题】使用 Laravel Eloquent / MySQL 比较多个数据库行值【英文标题】:Comparing multiple database row values with Laravel Eloquent / MySQL 【发布时间】:2017-11-18 03:50:19 【问题描述】:

我在我的项目中使用 Laravel,并且有一个 mysql 表,如下所示:

| User_id | technology | years_experience |
| 1       | php        |  4               |
| 2       | AngularJS  |  2               |
| 1       | html       |  2               |

目前我正在使用仅支持一个条件的标准 where 查询

Table::where([
['technology', '=', 'PHP'],
['years_experience', '>', 2]
])->get()->pluck('user_id');

如果我想检索 PHP > 2 AND HTML > 1 的所有 User_id,如何按 User_id 过滤和分组结果?

【问题讨论】:

【参考方案1】:

尚未对此进行测试,但理想情况下我想这就是您所需要的

Table::where('technology', '=', 'PHP')->andWhere('years_experience', '>', 2)->get()->pluck('user_id')->andWhere('user_id','=',ANYUSERID)->groupBy('user_id')->get(['user_id','technology','years_experience']);

【讨论】:

【参考方案2】:

问题是(condition1 AND condition2) AND (condition3 AND condition4)

你可以这样做:

Table::where(function($query)
    $query->where('technology', '=', 'PHP')->where('years_experience', '>', 2);
)->where(function($query) 
    $query->where('technology', '=', 'HTML')->where('years_experience', '=', 1);
)->get()->pluck('user_id');

【讨论】:

产生 0 个结果。还尝试使用数据库管理器中 toSql() 函数生成的 SQL【参考方案3】:

使用 WHERE / AND 的问题在于它不会比较行级别的值,而是跨列搜索匹配的值

“hack”是使用 HAVING()。这是有效的解决方案:

Table::groupBy('user_id')
->havingRaw("sum(tech='PHP' AND experience>=2) > 0")
->havingRaw("sum(tech='HTML' AND experience>=1) > 0")
->get()
->pluck('user_id')

【讨论】:

以上是关于使用 Laravel Eloquent / MySQL 比较多个数据库行值的主要内容,如果未能解决你的问题,请参考以下文章

使用 Eloquent 的 Laravel 块方法

Laravel 5 - 使用 Mockery 模拟 Eloquent 模型

Laravel 验证使用 eloquent 或 raw 查询

Laravel/Eloquent 建议覆盖 trait 属性?

Laravel Eloquent使用小记

使用 Laravel 5.5 接收 [Illuminate\Database\Eloquent\MassAssignmentException] 电子邮件