I'm working with mongoDB and PHP (Laravel) and finding alot of difficulties in executing the complex queries on PHP (Laravel), all queries working smoothly on mongo Booster but when I execute them on PHP (Laravel) it really gives me tough time. Can any one help me out how could I execute them like raw queries on PHP (Laravel).
Raw queries in Laravel
Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Another Example
$result = DB => collection('PMS')->raw(function ($collection){
return $collection->aggregate(array(
array( '$match' => array( "PanelID" => "A00898" ) ),
array( '$project' => array( 'EventTS' => 1, 'MainsPower' => 1 ) ),
array(
'$unwind' => array(
'path' => "$MainsPower",
'includeArrayIndex' => "arrayIndex",
'preserveNullAndEmptyArrays' => true
)
),
array(
'$project' => array(
'_id' => 0,
'MainsPower' => 1,
'timestamp' => array(
"$add" => array(
"$EventTS",
array( "$multiply" => array( 60000, "$arrayIndex" ) )
)
)
)
)
));
});
Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:
$result = DB::select(
DB::raw('your query here')
);
Reference
Yes answers given by other is right but raw queries performing in Laravel is not good practice. Then why you are using Laravel Framework. You should use eloquent because if you change the db like mysql instead of mongo you need not to change quires. That's the power of Eloquent ORM.
Related
Background:
Mediawiki's PHP framework provides functions for creating SQL statements to be executed against the application. Creating a simple SELECT FROM WHERE statement is easy and well documented, but I'm trying to create a JOIN statement and I don't understand the documentation. The examples are fragmented and disjointed.
Current attempt:
The SQL I'm trying to recreate is as follows. Using phpmyadmin I've tested this code and it returns the results I need:
SELECT user.user_id, user.user_name, user.user_real_name, user.user_email
FROM user
LEFT JOIN ipblocks ON user.user_id = ipblocks.ipb_user
WHERE ipblocks.ipb_id IS NULL
Translating this into Mediawiki's framework looks something like this, but this code doesn't work. The function documentation is here.
$result = $this->dbr->select(
array( $this->dbr->tableName( 'user' )),
array( 'user_name', 'user_id', 'user_email' ),
array( 'ipb_id' => 'NULL'),
__METHOD__,
array( 'GROUP_BY' => 'user_id DSC' ),
array( 'ipblocks' => array( 'LEFT JOIN', 'user_id=ipb_user' ) )
);
The SQL generated by this code can be checked by calling selectSQLText() instead. This function returns the generated SQL rather than executing it. The calling convention is the same. THis results in the following SQL:
SELECT user_name,user_id,user_email
FROM `user`
WHERE ipb_id = 'NULL'
I can see why the function has returned this, but I don't understand why the last two parameters have been ignored. The GROUP_BY and JOIN parts have been ignored. Why is this and how do I correct the code?
Thanks.
I'm not an user of Mediawiki, I've just glossed over the function documentation. As for grouping, I believe you should use GROUP BY array key, not GROUP_BY. As for joins, I think you must include ipblocks table in $table parameter in order to use it in $join_conds.
So, try this:
$result = $this->dbr->select(
array( 'user', 'ipblocks' ),
array( 'user_name', 'user_id', 'user_email' ),
array( 'ipb_id' => null),
__METHOD__,
array( 'GROUP BY' => 'user_id DSC' ),
array( 'ipblocks' => array( 'LEFT JOIN', 'user_id=ipb_user' ) )
);
I have a MongoDB query that is verified as 100% working ( Using MongoHub I have connected to the Replica Set and run the query and received results ), but when converting this query to PHP and attempting to run it through MongoCollection->aggregate(), I fail to get a return/result of any kind whatsoever ... not even an error.
Here is the query, as put into a PHP Array ( as MongoCollection requires ):
$query = array(
'$match' => array(
'$and' => array(
'make' => $props[0],
'model' => $props[1],
'makeYear' => (integer)$props[2],
'status' => 'Active'
)
),
'$group' => array(
'_id' => null,
'marketTotal' => array('$sum' => '$price'),
'count' => array('$sum' => 1)
)
);
The code to run the query is a simple one-liner calling aggregate.
As I don't get errors ... or a log showing any sort of error ... I'm kind of at a total loss here. Is anyone familiar with using PHP w/ MongoDB able to see what I might be doing wrong?
Turns out I was simply missing a layer of arrays ... wrapping each piece of the '$and' array in its own array ... so array('make' => $props[0]), etc ... made it work.
Fun stuff. MongoDB queries are easy. Translating them into PHP-compatible arrays is apparently very difficult and requires a lot of guesswork because it's not 1-to-1
I'm using the containable behavior to look at several tables.
$this->paginate = array(
'contain' => array(
'Co' => array('fields' => array('ref')),
'CoItemType' => array('fields' => array('name')),
'Casing' => array(
'fields' => array('id','barcode','CONCAT(plant_dot,size_dot,product_line_dot,production_week) as dot'),
'Customer' => array('fields' => array('company_name')),
)
)
);
This works as expected. However I am integrating this with jQuery datatables and the way dataTables passes over conditions it does not specifiy a field. So I'd like to do conditions outside of the contains like so...
'conditions' = array(
'OR' => array(
array("Table.field_name LIKE " => '%'.$parameter.'%'),
array("Table.field_name LIKE " => '%'.$parameter.'%'),
array("Table.field_name LIKE " => '%'.$parameter.'%')
)
)
Of course this is not possible since the containable behavior wants you to include the conditions under the tables key in the contain array. This is frustrating, does anyone have a solution or workaround around to this problem?
I am using CakePHP 2.x
Use Linkable Behavior as noted in comments.
It feels like I've tried everything. I'm building a newsfeed of sorts from 2 data tables 'Spec' and 'Update'. Here is the CakePHP code.
// Setup pagination
$this->paginate = array(
'Spec' => array(
'fields' => array(
'Spec.id',
'Spec.name'
),
'limit' => 10,
'conditions' => array(
'Spec.car_id' => $id
),
'order' => array(
'Spec.created' => $orderSetting
)
),
'Update' => array(
'fields' => array(
'Update.id',
'Update.name'
),
'limit' => 10,
'conditions' => array(
'Update.car_id' => $id
),
'order' => array(
'Update.created' => $orderSetting
)
)
);
$updates = $this->paginate(array('Spec', 'Update'));
This is returning an SQL error.
SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Update' at line 1
The problem is this line - it only allows for one item?
$updates = $this->paginate(array('Spec', 'Update'));
eg.
$updates = $this->paginate('Spec');
Which, of course, isn't what I'm looking for.
Any help or direction much appreciated.
The paginate() function does not allow multiple Models as a parameter, as it is really only a proxy to the find() function (see docs). Your second parameter ('Update') will be treated as a condition for the find() call - which results in the SQL error.
You will need to create a find() call on one model, that returns all the data you want. You can include data from the other model using model relations and possibly the ContainableBehavior.
Another way would be two different find() operations and manually combining the results. But the you would also have to handle the pagination manually.
I need to use a query builder that generates SQL statements containing placeholders.
It should:
Generate SQL statements containing placeholders(:placeHolder or ?)
Have no object mapping
Return the query as a string or similar
Work with all major databases(e.g. Oracle, MySQL)
I am thinking about something like this:
QueryBuilder::select(
'db' => 'MySQL'
'from' => 'users',
'fields' => array(
'user_id' => 'id'
),
'where' => array(
'AND' => array(
/**
* ...conditions...
*/
)
),
'ljoin' => array(
'Group' => array(
'from' => 'groups'
/**
* ...stuff...
*/
)
)
);
I looked into Doctrine2 but it needs object mapping. And a lot of initial configuration.
I looked into Doctrine2 DBAL and it does not handle INSERT queries.
Note: Queries are generated in development stage and saved as plain text for each supported database engine.
Thank you in advance.
Try the Doctrine 2 ORM Query builder very versatile and works with most DBMS systems more at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html
An example is the Code Igniter Active Record, you can build querys like:
$this->db->select('field_one, field_two')
->from('mytable')
->where(array('field' => 'value', 'field' => 'value'))