Laravel使用DB :: table作为自定义字段

时间:2014-03-16 07:03:08

标签: php laravel laravel-4

我想将COUNT等自定义字段用于DB::table()。以下代码不正确

例如:

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

$query =  DB::select('select * , count( DISTINCT ipAddress ) , count( ipAddress )
          from webInformation where webLink = ?', array(1))->first();

我有两个问题

  1. 我不能使用first()
  2. 我不能使用计数

2 个答案:

答案 0 :(得分:1)

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

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

计数结果将在diffCount键中显示。

答案 1 :(得分:1)

您也可以执行此操作,以便正确访问密钥。

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

现在,您可以通过密钥count而不是像count(ipAddress)这样的密钥来访问它。