laravel框架 count()使用小结

直接上源码:

/**
 * Retrieve the "count" result of the query.
 *
 * @param  string  $columns
 * @return int
 */
public function count($columns = '*')
{
    return (int) $this->aggregate(__FUNCTION__, Arr::wrap($columns));

}

从源码我们可以看出,count()函数是用来计算某一个字段的总记录数,若没有给函数传参数,则是默认计算表中得到记录数

注意,count传参只能传字段名,返回结果是个整数。这个函数加上约束条件了可以可以计算出确定的字段值的数量。

例如:

public function getRecordByUserIdAndOpernId($opern_id,$user_id)
{
    $result = DB::table($this->table)
        ->where(['opern_id'=>$opern_id, 'user_id'=>$user_id])
        ->count();
    return $result;

count()加where()组合便可以计算出‘opern_id’=>$opern_id, 'user_id'=>$user_id的记录数。

猜你喜欢

转载自blog.csdn.net/chaoman3171/article/details/81174472