找不到列:在laravel中执行

时间:2018-12-11 10:45:52

标签: mysql laravel laravel-5.5 laravel-query-builder

我正在做一个维护项目,其中所有都是sql查询,但是我想将其转换为laravel。这是下面的查询:-

$members = Member::select('members.id','members.first_name',
                          'members.surname','members.username','members.password',
                          'members.email','user_access.active',
                          DB::raw('SUM( IF (user_access.active = "y", 1, 0) ) as acount'))
        ->join('user_access','user_access.member_id','=','members.id')
        ->where('special_access','=','n')
        ->groupby('user_access.member_id')
        ->having('acount','>','0')
        ->orderby('members.id','desc')
        ->orderby('members.username','ASC')
        ->orderby('user_access.note','DESC')
        ->paginate(30);

当我执行查询时,这给了我错误。出现在有子句的错误下面

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'acount' in 'having clause' (SQL: select count(*) as aggregate from `members` inner join `user_access` on `user_access`.`member_id` = `members`.`id` where `special_access` = n group by `user_access`.`member_id` having `acount` > 0)

1 个答案:

答案 0 :(得分:1)

我想类似的东西会对您有所帮助。

$userAccess = DB::table('user_access')
    ->where('special_access','=','n')
    ->where('active','y')
    ->groupby('member_id');

Member::select([
    'members.id', 
    'members.first_name', 
    'members.surname', 
    'members.username', 
    'members.password', 
    'members.email', 
    'user_access.active'
])->joinSub($userAccess, 'user_access', function($join){
    $join->on('user_access.member_id', '=', 'members.id');
})->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderBy('user_access.note','asc')
->paginate(30);

OR

$members = Member::select([
    'members.id', 
    'members.first_name', 
    'members.surname', 
    'members.username', 
    'members.password', 
    'members.email', 
    'user_access.active'
])->join('user_access', function($join){
    $join->on('user_access.member_id', '=', 'members.id')->on('user_access.active', '=', DB::raw('"y"'));
})
    ->where('special_access','=','n')
    ->groupby('user_access.member_id')
    ->orderby('members.id','desc')
    ->orderby('members.username','ASC')
    ->orderby('user_access.note','DESC')
    ->paginate(30);
  

apokryfos在评论中所述:

     

分页器将尝试获取查询的计数,并在执行此操作时将其从所有选择中删除,从而导致此错误。

如果您只需要使用user_access.active = "y"的记录,则无需首先选择它们,然后尝试用HAVING过滤掉它们