Laravel 5.4 SQLSTATE [42S22]:找不到列(但列存在!)

时间:2017-06-10 06:56:30

标签: php mysql laravel

这是一个非常奇怪的错误,也许我忽略了一些事情:我正在运行这个查询:

    $getUnsupportedOS = Nessus::select('nessus_tags.unsupported_os')
        ->where('nessus_tags.unsupported_os', '=', 'true')
        ->join('nessus_tags','nessus_results.tagID','=','nessus_tags.tagID')
        ->whereRaw('nessus_results.scan_end >= UNIX_TIMESTAMP((NOW() - INTERVAL '.'1'.' MONTH))')
        ->count();

但它给了我这个错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'nessus_tags.unsupported_os' in 'where clause' (SQL: select count(*) as aggregate from `nessus_results` inner join `nessus_tags` on `nessus_results`.`tagID` = `nessus_tags`.`tagID` where `nessus_tags`.`unsupported_os` != and nessus_results.scan_end >= UNIX_TIMESTAMP((NOW() - INTERVAL 1 MONTH)))

但是,正如您在附图('列存在')中看到的那样,该表确实存在。我错过了什么?

提前感谢您的帮助。

祝你好运!

column exists

1 个答案:

答案 0 :(得分:0)

使用表格加入模型通常是一个红旗。您应该创建相关模型并定义关系:

class Nessus {
       protected $table='nessus_results';
       //model

      public function tags() {
             return $this->hasMany(NessusTag::class, 'tagID');
      }  
}

然后你可以这样做:

$getUnsupportedOS = Nessus::withCount([ "tags" => function ($q) {
        return $q->where("unsupported_os","=","true"); 
 }])->whereRaw('scan_end >= UNIX_TIMESTAMP((NOW() - INTERVAL '.'1'.' MONTH))')->first();

然后计数在:$getUnsupprtedOS->tags_count