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

时间:2017-02-17 15:03:39

标签: php mysql laravel

我有一个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();

1 个答案:

答案 0 :(得分:0)

似乎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();

未经过测试