clrghouz/app/Traits/UseMongo.php

93 lines
1.8 KiB
PHP
Raw Normal View History

<?php
/**
* Models that store data in Mongo
*/
namespace App\Traits;
2021-10-26 12:19:55 +00:00
use Illuminate\Database\Eloquent\Collection;
trait UseMongo
{
/**
* Resolve a connection instance.
* We need to do this, because our relations are in pgsql and somehow loading a relation changes this models
* connection information. Using protected $connection is not enough.
*
* @param string|null $connection
*/
public static function resolveConnection($connection = null)
{
return static::$resolver->connection('mongodb');
}
/* ATTRIBUTES */
public function getMsgAttribute($value): string
{
return utf8_decode($value);
}
public function setMsgAttribute($value): void
{
$this->attributes['msg'] = utf8_encode($value);
}
2021-08-26 12:32:32 +00:00
public function getSubjectAttribute($value): string
{
return utf8_decode($value);
}
public function setSubjectAttribute($value): void
{
$this->attributes['subject'] = utf8_encode($value);
}
2021-10-26 12:19:55 +00:00
/* METHODS */
2021-11-20 06:58:46 +00:00
public static function countGroupBy(array $fields,array $where=[]): Collection
2021-10-26 12:19:55 +00:00
{
$query = collect();
if (count($where)) {
$where_condition = [];
foreach ($where as $key => $values) {
if (! is_array($values))
throw new \Exception('Where values must be an array.');
$where_condition[$key] = ['$in' => $values];
}
$query->push([
'$match' => $where_condition
]);
}
2021-11-20 06:58:46 +00:00
$gb = collect();
foreach ($fields as $field)
if (is_array($field)) {
foreach ($field as $k=>$v) {
$gb->put('datetime',['$dateToString'=>['format'=>$v,'date'=>'$'.$k]]);
}
} else {
$gb->put($field,'$'.$field);
}
2021-10-26 12:19:55 +00:00
$query->push([
'$group' => [
2021-11-20 06:58:46 +00:00
'_id' => $gb->toArray(),
2021-10-26 12:19:55 +00:00
'count' => ['$sum' => 1]
]
]);
return (new self)
->groupBy($field)
->raw(function($collection) use ($query) {
return $collection->aggregate(
$query->toArray()
);
});
}
}