首页 > 解决方案 > 如何在 eloquent 的多个关系字段上使用 count 和 orderBy?

问题描述

我要做的是为表数据设置服务器端配置。所以我有一个模型CounterLog,它有 3 个关系集 [ belongsTo] category, location, user. 我想要一个查询来过滤所有CounterLog数据,包括关系、withoffsetlimit方法orderBy集,同时检索所有过滤后的行,忽略offsetand limit。这是我到目前为止所管理的,也许可以更好地理解我想要的东西:

$search_query = function($q) use ($search) {
    $q->where('name', 'like', '%' . $search . '%');
};

$query = CounterLog::where('created_at', 'like', '%' . $search . '%')
->orWhereHas('category', $search_query)
->orWhereHas('location', $search_query)
->orWhereHas('user', $search_query);

$logs = $query->offset($offset)->limit($limit)->get();
$logs_total = $query->offset(0)->count();

在我使用的最后一行中,$query->offset(0)因为某种原因 ifoffset设置为一个数字$logs_total变为 0。我不确定这是不是正确的方法..但即使这样我也不知道如何使用orderByfor ex。category.name.

我知道我总是可以在 eloquent 中使用原始查询,但我想知道是否有办法使用 ORM 和关系。如果您能帮我解决这个问题,我将不胜感激……因为斗争是真实的。

非常感谢 :)


显然我还没有使用 ORM 的解决方案,所以我使用“原始”查询来解决:

$query = $this->db->table('counter_logs')
                ->leftJoin('categories', 'counter_logs.category_id', '=', 'categories.id')
                ->leftJoin('locations', 'counter_logs.location_id', '=', 'locations.id')
                ->leftJoin('users', 'counter_logs.user_id', '=', 'users.id');
                ->where('counter_logs.created_at', 'like', '%' . $search . '%')
                ->orWhere('categories.name', 'like', '%' . $search . '%')
                ->orWhere('locations.name', 'like', '%' . $search . '%')
                ->orWhere('users.name', 'like', '%' . $search . '%');
                ->select('counter_logs.id as id', 'categories.name as category', 'locations.name as location', 'users.name as user', 'counter_logs.created_at as date'); 

$json['total'] = $query->count();
$logs = $query->offset($offset)->limit($limit)->orderBy($sort, $order)->get();

标签: phpeloquentsql-order-byrelationship

解决方案


尝试交换语句:

$logs_total = $query->count();
$logs = $query->offset($offset)->limit($limit)->get();

或克隆基本查询,如下所示:

$total_count_query = clone $query;
$logs = $query->offset($offset)->limit($limit)->get();
$logs_total = $total_count_query->count();

推荐阅读