gpt4 book ai didi

PHP - 将参数从数组传递到 SQL 查询

转载 作者:行者123 更新时间:2023-11-30 22:04:08 27 4
gpt4 key购买 nike

我有一个SQL查询,我想根据不同的场景传递不同的参数。我不确定该怎么做。这是查询:

$data = Engagement::leftJoin('user_engagement', 'engagements.id', '=', 'user_engagement.engagement_id')
->select('engagement_id', 'engagements.question', 'engagements.id')
->selectRaw('count(*) as count')
->whereBetween('user_engagement.created_at', [$from.' 00:00:00', $to.' 00:00:00'])
->groupBy('user_engagement.engagement_id')
->orderBy('count', 'DESC')
->take(5)
->get()->toArray();

所以,我想做的事情看起来像这样:

            $model = new Engagement;
$leftJoin = ['user_engagement', 'engagements.id', '=', 'user_engagement.engagement_id'];
$select = ['engagement_id', 'engagements.question', 'engagements.id'];
$whereBetween = 'user_engagement.created_at';
$groupBy = 'user_engagement.engagement_id';

$data = $model->leftJoin($leftJoin)
->select($select)
->selectRaw('count(*) as count')
->whereBetween($whereBetween, [$from.' 00:00:00', $to.' 00:00:00'])
->groupBy($groupBy)
->orderBy('count', 'DESC')
->take(5)
->get()->toArray();

最佳答案

似乎 leftJoinselect 方法都采用多个参数而不是一个参数数组。此修复应该有效,但不推荐:

$leftJoin = [
'user_engagement',
'engagements.id',
'=',
'user_engagement.engagement_id'
];
$select = [
'engagement_id',
'engagements.question',
'engagements.id'
];



data = $model->leftJoin($leftJoin[0], $leftJoin[1], $leftJoin[2], $leftJoin[3])
->select($select[0], $select[1], $select[2])

我建议将您的数组拆分为单独的变量或为此目的创建一个对象。


您还可以使用更高级的方式使用 ReflectionMethod::invokeArgs

我的猜测是它看起来这样:

$model = new Engagement;
$leftJoin = ['user_engagement', 'engagements.id', '=', 'user_engagement.engagement_id'];
$select = ['engagement_id', 'engagements.question', 'engagements.id'];
$whereBetween = 'user_engagement.created_at';
$groupBy = 'user_engagement.engagement_id';

$reflectLeftJoin = new ReflectionMethod('Engagement', 'leftJoin');
$reflectSelect = new ReflectionMethod('Engagement', 'select');

$reflectSelect->invokeArgs($model, $reflectLeftJoin->invokeArgs($model, $leftJoin))
->selectRaw('count(*) as count')
->whereBetween($whereBetween, [$from.' 00:00:00', $to.' 00:00:00'])
->groupBy($groupBy)
->orderBy('count', 'DESC')
->take(5)
->get()->toArray();

未测试

关于PHP - 将参数从数组传递到 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42301099/

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