如何在雄辩的子查询中使用非匿名方法?

时间:2019-04-03 10:00:01

标签: php laravel eloquent anonymous-function

雄辩地说,我们可以在where方法中使用匿名函数作为第二个参数。我想使用非匿名类方法代替它。但对我不起作用。

常规匿名模式:(使用旧样式)-我不想使用此方法

           ->whereIn('plantation_id', function ($query) use ($plantationId){
          $query->select('id')
          ->from('plantations')
          ->whereBetween('_lft', [
              DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
              DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
              ]);

       });

我要使用:

查询:

 ->whereIn('plantation_id', Plantation::getIdsByParent($query, $plantationId));

种植园等级:

class Plantation extends Model
{
 ....
     public static function getIdsByParent($query, $plantationId)
    {
        return $query->select('id')
            ->from('plantations')
            ->whereBetween('_lft', [
                DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
                DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
            ]);
    }
}

2 个答案:

答案 0 :(得分:1)

如果您不想重复代码,则可以执行以下操作:

->whereIn('plantation_id', function($query) use ($plantationId) {
    return Plantation::getIdsByParent($query, $plantationId);
});

仍然具有匿名功能,但是您正在使用已经定义的逻辑而没有将其复制粘贴。

答案 1 :(得分:0)

您可以发布所收到的错误吗?

据我了解,您希望使用getIdsByParent获取ID的集合/数组。

我的理解是,您的函数将返回QueryBuilder实例以返回集合,您需要在最后添加-> get()。这对您有用吗?

     public static function getIdsByParent($query, $plantationId)
    {
        return $query->select('id')
            ->from('plantations')
            ->whereBetween('_lft', [
                DB::raw('(SELECT `_lft` FROM `plantations` WHERE id = ' . $plantationId .')'),
                DB::raw('(SELECT `_rgt` FROM `plantations` WHERE id = '. $plantationId .')')
            ])->get();
    }

如果您想要一个数组,则应该在末尾添加一个简单的-> toArray()。

也许为此也可以使用查询范围。

Laravel Docs Query Socpes