Php Laravel对自定义字段使用DB::table

Php Laravel对自定义字段使用DB::table,php,laravel,laravel-4,Php,Laravel,Laravel 4,我想在DB::table()中使用自定义字段,如COUNT等。下面的代码不正确 例如: $query = DB::table('webInformation') ->select('id', 'count( DISTINCT ipAddress )') ->where('webLink = 1 ')->first(); 或 我有两个问题 我不能用first() 我不能用计数 使用DB::raw避免Laravel转义查询 $query = DB::table('webInf

我想在
DB::table()
中使用自定义字段,如
COUNT
等。下面的代码不正确

例如:

$query =  DB::table('webInformation')
->select('id', 'count( DISTINCT ipAddress )')
->where('webLink = 1 ')->first();

我有两个问题

  • 我不能用first()
  • 我不能用计数

  • 使用DB::raw避免Laravel转义查询

    $query =  DB::table('webInformation')
    ->select('id', DB::raw('count( DISTINCT ipAddress ) as diffCount'))
    ->where('webLink',=,'1 ')->first();
    

    计数结果将在
    diffCount
    键中提供。

    您也可以这样做,以便正确访问键

    $q = DB::table('webInformation')
           ->select('id', 'ipAddress', DB::raw("count(ipAddress) AS total"))
           ->where('webLink',=,'1 ')
           ->groupBy('ipAddress')
           ->get();
    

    现在,您可以通过键
    count
    来访问它,而不是像
    count(ipAddress)

    这样的键,如果您使用此列,则可以按ipAddress添加组
    $q = DB::table('webInformation')
           ->select('id', 'ipAddress', DB::raw("count(ipAddress) AS total"))
           ->where('webLink',=,'1 ')
           ->groupBy('ipAddress')
           ->get();