mysql - 将原始 MySQL 转换为 Eloquent
问题描述
有人可以帮我将此 SQL 查询转换为 Eloquent 吗?
SELECT SUM(amount) as amount
FROM recurrings
WHERE space_id = 1
AND YEAR(starts_on) <= 2019
AND MONTH(starts_on) <= 08
AND ((YEAR(ends_on) >= 2019 AND MONTH(ends_on) >= 08) OR ends_on IS NULL)
提前致谢
解决方案
假设表的模型recurrings
被称为Recurring
:
# App\Recurring.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recurring extends Model
{
// This table name follows the Laravel naming convention so this line isn't necessary.
// This is just to be explicit. Or if you want to give the model a different name.
// https://laravel.com/docs/5.8/eloquent#defining-models
protected $table = 'recurrings';
// Since you're using dates, it's best to mutate them into Carbon objects.
// It will make dealing with them easier when using php.
// https://laravel.com/docs/5.8/eloquent-mutators#date-mutators
protected $dates = ['starts_on', 'ends_on'];
}
$recurrings = Recurring::selectRaw('SUM(amount)') // SELECT SUM(amount) FROM recurrings
->where('space_id', 1) // WHERE space_id = 1
->whereYear('starts_on', '<=', '2019') // AND YEAR(starts_on) <= 2019
->whereMonth('starts_on', '<=', '08') // AND MONTH(starts_on) <= 08
->where(function($q1) { // AND (
$q1->where(function($q2) { // (
$q2->whereYear('ends_on', '>=', '2019') // YEAR(ends_on) >= 2019
->whereMonth('ends_on', '>=', '08'); // AND MONTH(ends_on) >= 08
}) // )
->orWhereNull('ends_on'); // OR ends_on IS NULL
})->get(); // )
如果您没有模型,请使用DB::table('recurrings')->...
而不是Recurring::...
https://laravel.com/docs/5.8/queries
使用查询生成器的connection
和toSql()
方法,我能够测试此查询是否返回了您在控制台中要求的内容。
$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.4 — cli) by Justin Hileman
\DB::connection('mysql')->table('recurrings')->selectRaw('SUM(amount)')->where('space_id', 1)->whereYear('starts_on', '<=', '2019')->whereMonth('starts_on', '<=', '08')->where(fun
ction($q1) { $q1->where(function($q2) { $q2->whereYear('ends_on', '>=', '2019')->whereMonth('ends_on', '>=', '08'); })->orWhereNull('ends_on'); })->toSql();
=> "select SUM(amount) from `recurrings` where `space_id` = ? and year(`starts_on`) <= ? and month(`starts_on`) <= ? and ((year(`ends_on`) >= ? and month(`ends_on`) >= ?) or `ends_on`
is null)"
推荐阅读
- python - 在 trimesh 中保存带纹理的 GLB 文件
- html - 如何使输入弹出并显示全部内容
- scikit-learn - Pycaret - 'Make_Time_Features' 对象没有属性 'list_of_features'
- r - 如何从 R 中的函数返回迭代更新的数据框?
- java - E/Volley:[2342] NetworkUtility.shouldRetryException:意外响应代码 400
- python - QLineEdit 导致 QPushButton 出现一些问题
- pandas - 如何返回熊猫中两列值之间的差异
- colors - 代号一 - 在 Maven 项目中更改状态栏颜色
- vhdl - 端口映射后的信号关联-VHDL
- sql - 在第二个表上使用 SUM 连接两个表