This is my MongoDB query
db.getCollection('fe_report').aggregate([{
$match:
{ date: { $gte: ISODate("2017-07-01T00:00:00.000Z"),
$lte: ISODate("2017-07-19T00:00:00.000Z")} } },
{
$group:
{
_id :"$employee_id_fk",
no_of_kms : {$sum: "$no_of_kms"},
no_of_orders: {$sum: "$no_of_orders"},
}
}
]
)
i need to execute this query from PHP
config/mongo.php
$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';
libraries/Mongo.php
class CI_Mongo extends Mongo
{
var $db;
function CI_Mongo()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo
if ($server)
{
parent::__construct($server);
}
else
{
parent::__construct();
}
$this->db = $this->$dbname;
}
}
And a sample controller
controllers/posts.php
class Posts extends Controller
{
function Posts()
{
parent::Controller();
}
function index()
{
$posts = $this->mongo->db->posts->find();
foreach ($posts as $id => $post)
{
var_dump($id);
var_dump($post);
}
}
function create()
{
$post = array('title' => 'Test post');
$this->mongo->db->posts->insert($post);
var_dump($post);
}
}
try this it work for u
You can use the aggregate function for grouping the fields by ID and computing sum for any columns (only for integer type)
$from = $from.".000Z"; // if you need to filter by date range
$to = $to.".000Z"; // from date and to date("2017-07-22 00:00:00.000Z")
$where = array( array(
'$match' => array(
'date' => array(
'$gte' => new MongoDate(strtotime($from)),
'$lte' =>new MongoDate(strtotime($to)))
)
),
array(
'$group' => array(
'_id' => '$employee_id_fk', // grouping by ID
'no_of_kms' => array(
'$sum' => '$no_of_kms' ' // summing up the KM's fields for the grouped columns
),
'no_of_orders' => array(
'$sum' => '$no_of_orders
)
)
)
);
$data = $this->maggregate('fe_report',$where); // passing it to the maggregate function
// maggregate function()
public function maggregate($table, $where){
$mdb = new MongoClient("localhost"); // establishing mongodb connection
$connect = $m->selectDB("examples")->selectCollection($table);
$result = $connect->aggregate($where);
connect->close();
return $result;
}
Related
i'm new in graphql.
I'm try to config graphql mutation via siler+swoole php framework, that use webonyx/graphql-php.
When i post query i'm get error "Schema is not configured for mutations", but it's configured in my shema.
My index
$typeDefs = file_get_contents(__DIR__.'/schema.graphql');
$resolvers = include __DIR__.'/resolvers.php';
$schema = GraphQL\schema($typeDefs, $resolvers);
GraphQL\execute($schema, GraphQL\request()->toArray(), [], [])
schema.graphql :
schema {
query: Query
mutation: Mutation
}
type Query {
clusters: [Cluster!]!
}
type Cluster {
id: Int
title: String
}
type Mutation {
addCluster(title: String!): Cluster!
}
resolver.php
<?php
use RedBeanPHP\R;
//R::setup('sqlite:'.__DIR__.'/db.sqlite');
$clusters = [
'clusters' => function () {
return R::findAll('clusters');
},
];
$queryType = [
'clusters' => function () {
return R::findAll('clusters');
},
];
$mutationType = [
'addCluter' => function ($root, $args) {
$title = $args['title'];
$cluster = R::dispense('cluster');
$cluster['title'] = $title;
R::store($cluster);
return $cluster;
},
];
return [
'Cluster' => $clusters,
'Query' => $queryType,
'Mutation' => $mutationType,
];
And my query is:
mutation addCluster($clusterName: String) {
addCluster(clusterName: $clusterName) {
id
}
}
The response says:
Schema is not configured for mutations
I'm trying to add a array to a json file using php.
How I want it to look (formatting does not matter):
{
// Already stored in json file
"swagg_ma_blue":{
"user":"swagg_ma_blue",
"admin":true,
"user_id":"000"
},
// Should be added using php
"dnl":{
"user":"dnl",
"admin":"true",
"user_id":"000"
}
}
How my outcome actually looks like:
{"swagg_ma_blue":{"user":"swagg_ma_blue","admin":true,"user_id":"000"},"0":{"user":"d4ne","admin":true,"user_id":"000"}}
As you see the array index/key of the second element is called "0" but I need it to have the user value.
My code:
<?php
class add_mod_class {
function __construct($username, $status){
$this->username = $username;
$this->status = $status;
$this->user_id = '000';
$this->json_file = 'includes/json/mods.json';
}
function get_json(){
$json_content = file_get_contents($this->json_file);
$json = json_decode($json_content, true);
return $json;
}
function mod_handler(){
if($this->status == 'admin'){
return true;
}else{
return false;
}
}
function add_mod(){
$mods = $this->get_json();
$data = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
array_push($mods, $data);
$new_json_string = json_encode($mods);
return $new_json_string;
}
}
?>
First idea was to use was:
$data[$this->username] = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
But this would still return "0": in it. I Would appreciate every kind of help.
Your first approach was fine, except you should assign to $mods array instead of $data. Here is the corrected function:
function add_mod(){
$mods = $this->get_json();
$mods[$this->username] = array(
'user' => $this->username,
'admin' => $this->mod_handler(),
'user_id' => $this->user_id
);
$new_json_string = json_encode($mods);
return $new_json_string;
}
I was following this book to install the ZendSearh on the application, I did exactly as it's written and I'm getting a Fatal error: Class 'ZendSearch\Lucene\Lucene' not found in /var/www/CommunicationApp/module/Users/src/Users/Controller/SearchController.php on line 107
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\Headers;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Users\Form\RegisterForm;
use Users\Form\RegisterFilter;
use Users\Model\User;
use Users\Model\UserTable;
use Users\Model\Upload;
use Users\Model\ImageUpload;
use Users\Model\ImageUploadTable;
use ZendSearch\Lucene;
use ZendSearch\Lucene\Document;
use ZendSearch\Lucene\Index;
class SearchController extends AbstractActionController
{
protected $storage;
protected $authservice;
public function getAuthService()
{
if (! $this->authservice) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
public function getIndexLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['search_index'])) {
return $config['module_config']['search_index'];
} else {
return FALSE;
}
}
public function getFileUploadLocation()
{
// Fetch Configuration from Module Config
$config = $this->getServiceLocator()->get('config');
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!empty($config['module_config']['upload_location'])) {
return $config['module_config']['upload_location'];
} else {
return FALSE;
}
}
public function indexAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$queryText = $request->getPost()->get('query');
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::open($searchIndexLocation);
$searchResults = $index->find($queryText);
}
// prepare search form
$form = new \Zend\Form\Form();
$form->add(array(
'name' => 'query',
'attributes' => array(
'type' => 'text',
'id' => 'queryText',
'required' => 'required'
),
'options' => array(
'label' => 'Search String',
),
));
$form->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Search',
'style' => "margin-bottom: 8px; height: 27px;"
),
));
$viewModel = new ViewModel(array('form' => $form, 'searchResults' => $searchResults));
return $viewModel;
}
public function generateIndexAction()
{
$searchIndexLocation = $this->getIndexLocation();
$index = Lucene\Lucene::create($searchIndexLocation); // line 107
$userTable = $this->getServiceLocator()->get('UserTable');
$uploadTable = $this->getServiceLocator()->get('UploadTable');
$allUploads = $uploadTable->fetchAll();
foreach($allUploads as $fileUpload) {
//
$uploadOwner = $userTable->getUser($fileUpload->user_id);
// id field
$fileUploadId= Document\Field::unIndexed('upload_id', $fileUpload->id);
// label field
$label = Document\Field::Text('label', $fileUpload->label);
// owner field
$owner = Document\Field::Text('owner', $uploadOwner->name);
if (substr_compare($fileUpload->filename, ".xlsx", strlen($fileUpload->filename)-strlen(".xlsx"), strlen(".xlsx")) === 0) {
// index excel sheet
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Xlsx::loadXlsxFile($uploadPath ."/" . $fileUpload->filename);
} else if (substr_compare($fileUpload->filename, ".docx", strlen($fileUpload->filename)-strlen(".docx"), strlen(".docx")) === 0) {
// index word doc
$uploadPath = $this->getFileUploadLocation();
$indexDoc = Lucene\Document\Docx::loadDocxFile($uploadPath ."/" . $fileUpload->filename);
} else {
$indexDoc = new Lucene\Document();
}
$indexDoc->addField($label);
$indexDoc->addField($owner);
$indexDoc->addField($fileUploadId);
$index->addDocument($indexDoc);
}
$index->commit();
}
}
It has its own repository on github.
https://github.com/zendframework/ZendSearch
You have to load it via composer or just download and put it under vendor folder.
I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?
Im currently making a google maps component for Joomla 2.5 using Gmaps3, im at the point where it populates the map with markers, but my foreach loop is only returning one object.
Code below:
My View.json.php:
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class LocateViewBranches extends JView
{
public function display($tpl = null)
{
$branch = $this->get('Branches');
foreach ($branch as $row) {
$response = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(),
);
$response['data'][] = array(
'city' => $row->branch_city,
);
}
echo json_encode($response);
}
}
and then in my Model;
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.model');
class LocateModelBranches extends JModel
{
public function getBranches()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__branches');
$query->where("published = 1");
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
}
Please shout if you guys need more code, but i think those are the two key files.
Thanks in advance
I've tidied up your display function. It will echo a multidimensional array in json format:
public function display($tpl = null)
{
$responses = array(); // assign each row to this array
$branch = $this->get('Branches');
foreach ($branch as $row)
{
// append row data to $responses array
$responses[] = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(
'city' => $row->branch_city
),
);
}
echo json_encode($responses);
}
I haven't tested it but it should be what you need.