繁体   English   中英

通过laatvel中的Spatie Activity-log的自定义属性进行搜索

[英]Search by custom properties of Spatie Activity-log in laravel

我正在使用ActivityLog记录我在Laravel中的用户活动。 此包非常适用于存储用户在我使用此包设置的各种模型上执行的所有createupdatedelete活动。

但是我现在面临一个问题。 我有如下的ActivityLog表 -

id | log_name | description | subject_id | subject_type | causer_id | causer_type | properties
----------------------------------------------------------------------------------------------------------------------------------------
7  | default  | created     |    4       | App\Response |   1       | App\User    |{"project_id":"22295","feature_id":"2","part_id":"1","response":"yes","user_id":1}

我需要通过存储在properties列中的project_id来获取此表的结果。 包文档说Activity是一个普通的Eloquent Model所以我们可以使用所有Eloquent提供的默认函数来与Activity模型一起使用。 但我不知道如何用Eloquent做到这一点。

现在,我通过以下代码实现这一目标 -

$activities = Activity::latest()->get()->filter(function($item) use($projectId) {
    $properties = $item->properties->toArray();
    if(isset($properties['attributes'])) 
        $properties = $properties['attributes'];

    return ($properties['project_id'] == $projectId);
});

我上面的代码的问题是它获取到目前为止记录的所有活动,因此它加载了所有存在的Activity模型,然后根据project_id进行过滤。 ActivityLog的大小增加到大量(比如100,000行)时,这将花费很多时间。 有没有人知道一种更好的方法来获取基于project_id的过滤结果而无需手动遍历所有行?

如果您的数据库支持JSON查询,则可以执行此操作。

$activities = Activity::where('properties->project_id', '22295')
            ->get();

不幸的是,据我所知,MariaDB不支持,所以这只适用于MySQL 5.7。

https://github.com/spatie/laravel-activitylog/issues/210

但是,如果你正在使用MariaDB的,你可以创建基于JSON数据虚拟列properties列,然后通过索引和查询。

https://mariadb.com/resources/blog/json-mariadb-102

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM