Laravel 如何使用 Eloquent 获取对象的行号?

标签 laravel laravel-4 eloquent

我想根据用户的创建日期了解用户的位置。我如何使用 Eloquent 做到这一点?

我希望能够做这样的事情:

User::getRowNumber($user_obj);

最佳答案

我想你想要 MySQL 解决方案,所以你可以这样做:

DB::statement(DB::raw('set @row:=0'));
User::selectRaw('*, @row:=@row+1 as row')->get();
// returns all users with ordinal 'row'

所以你可以实现这样的东西:
public function scopeWithRowNumber($query, $column = 'created_at', $order = 'asc')
{
    DB::statement(DB::raw('set @row=0'));

    $sub = static::selectRaw('*, @row:=@row+1 as row')
        ->orderBy($column, $order)->toSql();

    $query->remember(1)->from(DB::raw("({$sub}) as sub"));
}

public function getRowNumber($column = 'created_at', $order = 'asc')
{
    $order = ($order == 'asc') ? 'asc' : 'desc';

    $key = "userRow.{$this->id}.{$column}.{$order}";

    if (Cache::get($key)) return Cache::get($key);

    $row = $this->withRowNumber($column, $order)
        ->where($column, '<=',$this->$column)
        ->whereId($this->id)->pluck('row');

    Cache::put($key, $row);

    return $row;
}

这需要从表中选择所有行,直到找到您要查找的行,然后仅选择该特定行号。

它会让你这样做:
$user = User::find(15);

$user->getRowNumber(); // as default ordered by created_at ascending

$user->getRowNumber('username'); // check order for another column

$user->getRowNumber('updated_at', 'desc'); // different combination of column and order

// and utilizing the scope:
User::withRowNumber()->take(20)->get(); // returns collection with additional property 'row' for each user

由于此范围需要原始语句设置 @row每次都设置为 0,我们使用缓存 1 分钟以避免不必要的查询。

关于Laravel 如何使用 Eloquent 获取对象的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23408091/

相关文章:

php - 为什么 Laravel/Eloquent 不能使用 JOIN 进行预加载?

Laravel 5.5 类型错误:传递给 Illuminate\Auth\EloquentUserProvider::validateCredentials() 的参数 1 必须是一个实例

laravel - Snappy PDF 中未显示 Google 图表

laravel - 伪造 laravel 自定义 ssl 设置

php - Laravel 4.2 services.json 文件在主机的根目录下创建

mysql - Laravel 连接两个表(包括 null)

php - Laravel Eloquent : Accessing properties and Dynamic Table Names

php - Laravel 模型 : Where are model properties?

php - SQLSTATE[HY000] [2003] 无法在 '127.0.0.1' (61) 错误上连接到 MySQL 服务器 Laravel 4.1

laravel - 使用 URL::action() 时如何更改域