Cake PHP Use Conditions and Order By in Paginate - pagination

I'm trying to use Conditions and Order By in cake PHP paginate function of the Paginator helper
This is my code which I'm using
$this->set('equipment', $this->Paginator->paginate('Equipment',array('conditions' => array('Equipment.equipment_type_id' => 19), 'order' => array('Equipment.problem_count', 'Equipment.barcode DESC'))));
But it gives me this error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'conditions' in 'where clause'
SQL Query: SELECT Equipment.id, Equipment.equipment_type_id, Equipment.barcode, Equipment.problem_count, Equipment.description, Equipment.created, Equipment.modified, EquipmentType.id, EquipmentType.name, EquipmentType.created, EquipmentType.modified FROM unlibike.equipment AS Equipment LEFT JOIN unlibike.equipment_types AS EquipmentType ON (Equipment.equipment_type_id = EquipmentType.id) WHERE conditions = (19) AND order IN ('Equipment.problem_count', 'Equipment.barcode DESC') LIMIT 20
By looking at the SQL query generated it looks like Cake PHP is interpreting 'conditions' and 'Order' as a column.
Can Anyone Help me?

params in order of Paginator::paginate
* #param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
* #param string|array $scope Additional find conditions to use while paginating
* #param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
* on non-indexed, or undesirable columns. See PaginatorComponent::validateSort() for additional details
* on how the whitelisting and sort field validation works.
http://api.cakephp.org/2.6/class-PaginatorComponent.html#_paginate
Example :
$this->Paginator->settings = array(
'order'=>array('yourfields');
);
$this->Pagniator->paginate('Equipment', $conditionsArray ) ;

Related

Mapping data flow SQL query and Parameters failing

In my mapping dataflow I have simplified this down to dimdate just for the test
My parameters are
The source even tells you exactly how to enter the select query if you are using parameters which is what I'm trying to achieve
Then I import but get two different errors
for parameterizing a table`
SELECT * FROM {$df_TableName}
I get
This error from a select * or invidiual columns
I've tried just the WHERE clause (what I actually need) as a parameter but keep getting datatype mismatch errors
I then started testing multiple ways and it only allows the schema to be parameterised from my queries below
all of these other options seem to fail no matter what I do
SELECT * FROM [{$df_Schema}].[{$df_TableName}] Where [Period] = {$df_incomingPeriod}
SELECT * FROM [dbo].[DimDate] Where [Period] = {$df_incomingPeriod}
SELECT * FROM [dbo].[{$df_TableName}] Where [Period] = {$df_incomingPeriod}
SELECT * FROM [dbo].[DimDate] Where [Period] = 2106
I know there's an issue with the Integer datatype but don't know how to pass this to the query within the parameter without changing its type as the sql engine cannot run [period] as a string
Use CONCAT function in expression builder to build the Query in Dataflow.
concat(<this> : string, <that> : string, ...) => string
Note: Concatenates a variable number of strings together. All the variables should be in form of strings.
Example 1:
concat(toString("select * from "), toString($df_tablename))
Example 2:
concat(toString("select * from "), toString($df_tablename), ' ', toString(" where incomingperiod = "), toString($df_incomingPeriod))
Awesome, it worked like magic for me. I was struggling with parameterizing tables= names which I was passing through Array list.
Created a data flow parameter and gave this value:
#item().TABLE_NAME

How to construct a `select ... in` SQL query in nim?

I'm using nim and db_sqlite to fetch some rows with certain _ids from a database table. For example:
for row in db.fastRows("SELECT * FROM t WHERE _id IN (?, ?)", #["1", "2"]):
echo row
This works as expected, however, the sequence at the end is constructed dynamically at runtime, which means I need a variable amount of ? in the query. I end up creating a sequence with question marks, joining them, interpolating the string and turning it into a database query:
var qs : seq[string]
for id in ids:
qs.add("?")
let query_string = """SELECT * FROM t WHERE _id IN ($1)""" % join(qs, ",")
let query = SqlQuery(query_string)
for row in db.fastRows(query, ids):
echo row
Is there a better way to construct a select ... in query in nim? Ideally one with just one ? in the SqlQuery.
(For what it's worth, the current behavior is similar to other languages I've used)
you could do the replacement manually, here's one way using strformat and map
import strformat,db_sqlite,sequtils,strutils
#assuming ids is a seq[string] here
let query = sql(&"SELECT * FROM t WHERE _id IN ({ids.map(dbQuote).join(\",\")})")
for row in db.fastRows(query):
echo row

How to get related field value from database in odoo 11 and postgresql?

I am trying to get a related field value from database, but it showing column 'column_name' does not exist.
When i try to find out the value of product_id or using join to find the common data between sale.order and product.product Model . but it showing column 'column_name' does not exist.
In sale.order model the field defination is like
product_id = fields.Many2one('product.product', related='order_line.product_id', string='Product')
But when i try to join two table like below code to fetch all data as per product, like below code.
select coalesce(p.name,'Unassigned Product'), count(*) from sale_order o left join product_product p on o.product_id = p.id where o.state = 'sale' group by p.name;
It showing below error,
column o.product_id does not exist
LINE 1: ... from sale_order o left join product_product p on o.product_...
When i try to get data from sale_order table like below code.
select product_id from sale_order;
It showing below error.
column "product_id" does not exist
Can any one help me to get that value.
To access a related field from database , you have to use the store=True , keyword.
Rewrite your field definition as,
product_id = fields.Many2one('product.product', related='order_line.product_id', string='Product', store=True)
and uninstall and install the module.

Sails.js One to many performances

I have compared the sql query on sails.js with the other way of doing it, using waterline's ORM.
I did the following request : Get all countries from all continents and I compared both requests with wireshark.
The simple SQL query :
"SELECT * FROM countries AS cou INNER JOIN continents AS con ON (cou.continent_id=continent.id)"
And then I did the same defining a one to many associations between countries and continents and did the following request.
Continents.find().populate("countries").exec(function(err, result)) {
res.send(result)
}
With that way, it takes around 66 ms to return the result, considering I have 15 ms of network delay, I can go down to 50 ms by moving the node.js server.
When I do it with the sql query, it takes around 35ms, so I could go down to nearly 20ms, which is good for me.
Is there a way to get the same results using both methods? or will the sql query always be faster?
Actually, the query generated in such population is
1. Selection of parents :
select * from continent where ...
Selection of all countries of the retrieved continents.
(select * from country where continent_id = continent_1)
union
(select * from country where continent_id = continent_2)
union
...
union
(select * from country where continent_id = continent_n)
Regroup result (Affectation of every country to its continent by foreign key.
This implementation make easy the management of limit and skip clauses as the call :
Continents.find().populate("countries").limit(2).skip(1).exec(function(err,
result)) {
res.send(result)
}
should only return the second and the third country for every continent and such implementation as you can see generate one only query so DBMS will not be overloaded.

Subsonic 3 Simple Query inner join sql syntax

I want to perform a simple join on two tables (BusinessUnit and UserBusinessUnit), so I can get a list of all BusinessUnits allocated to a given user.
The first attempt works, but there's no override of Select which allows me to restrict the columns returned (I get all columns from both tables):
var db = new KensDB();
SqlQuery query = db.Select
.From<BusinessUnit>()
.InnerJoin<UserBusinessUnit>( BusinessUnitTable.IdColumn, UserBusinessUnitTable.BusinessUnitIdColumn )
.Where( BusinessUnitTable.RecordStatusColumn ).IsEqualTo( 1 )
.And( UserBusinessUnitTable.UserIdColumn ).IsEqualTo( userId );
The second attept allows the column name restriction, but the generated sql contains pluralised table names (?)
SqlQuery query = new Select( new string[] { BusinessUnitTable.IdColumn, BusinessUnitTable.NameColumn } )
.From<BusinessUnit>()
.InnerJoin<UserBusinessUnit>( BusinessUnitTable.IdColumn, UserBusinessUnitTable.BusinessUnitIdColumn )
.Where( BusinessUnitTable.RecordStatusColumn ).IsEqualTo( 1 )
.And( UserBusinessUnitTable.UserIdColumn ).IsEqualTo( userId );
Produces...
SELECT [BusinessUnits].[Id], [BusinessUnits].[Name]
FROM [BusinessUnits]
INNER JOIN [UserBusinessUnits]
ON [BusinessUnits].[Id] = [UserBusinessUnits].[BusinessUnitId]
WHERE [BusinessUnits].[RecordStatus] = #0
AND [UserBusinessUnits].[UserId] = #1
So, two questions:
- How do I restrict the columns returned in method 1?
- Why does method 2 pluralise the column names in the generated SQL (and can I get round this?)
I'm using 3.0.0.3...
So far my experience with 3.0.0.3 suggests that this is not possible yet with the query tool, although it is with version 2.
I think the preferred method (so far) with version 3 is to use a linq query with something like:
var busUnits = from b in BusinessUnit.All()
join u in UserBusinessUnit.All() on b.Id equals u.BusinessUnitId
select b;
I ran into the pluralized table names myself, but it was because I'd only re-run one template after making schema changes.
Once I re-ran all the templates, the plural table names went away.
Try re-running all 4 templates and see if that solves it for you.

Resources