cakephp sql join query in controller - sql

I'm new to CakePHP and stuck on this situation:
I'm developing a test system and I have following three tables: Category, SubCategory, Test
When I create a test, I store category_id, subcategory_id with other data in Test table
Now in TestsController, I want to read the number of records & rows matched by the query
I wish to execute queries similar to these:
Query 1
select count(*) from Test where user_id='$user_id' and category_id=$category_id and subcategory_id=$subcategory_id
Query 2
select
a.test_id,
a.test_name,
a.user_id,
a.test_type,
a.create_date,
a.create_time,
a.category_id,
a.subcategory_id,
a.randomize,
a.test_password
from Test a, Category b, SubCategory c
where user_id='$user_id' and
a.category_id=$category_id and
a.subcategory_id=$subcategory_id and
a.category_id=b.category_id and
a.subcategory_id=c.subcategory_id
Now, I don't want (I actually don't know) to use the $hasMany, $belongsTo etc.
I simply want to execute these queries in Controller & pass the data to the view
Note: In all simple cases, I used the CakePHP style of coding
I wish to know, how can I get an array of rows after executing Query 2
Is it possible to execute such query directly (like mysql_query)

you could create a function in Test Model and access the query, like:
class TestModel extends Model {
..
public function getQueryData($user_id, $cat_id, $subcat_id) {
return $this->query("SELECT a.test_id, a.test_name ..... ;");
}
}
and in Test controller, you could do:
$this->loadModel("Test");
$result = $this->Test->getQueryData($user_id, $cat_id, $subcat_id);

Related

How to modify value in column typeorm

I have 2 tables contractPoint and contractPointHistory
ContractPointHistory
ContractPoint
I would like to get contractPoint where point will be subtracted by pointChange. For example: ContractPoint -> id: 3, point: 5
ContractPointHistory has contractPointId: 3 and pointChange: -5. So after manipulating point in contractPoint should be 0
I wrote this code, but it works just for getRawMany(), not for getMany()
const contractPoints = await getRepository(ContractPoint).createQueryBuilder('contractPoint')
.addSelect('"contractPoint".point + COALESCE((SELECT SUM(cpHistory.point_change) FROM contract_point_history AS cpHistory WHERE cpHistory.contract_point_id = contractPoint.id), 0) AS points')
.andWhere('EXTRACT(YEAR FROM contractPoint.validFrom) = :year', { year })
.andWhere('contractPoint.contractId = :contractId', { contractId })
.orderBy('contractPoint.grantedAt', OrderByDirection.Desc)
.getMany();
The method getMany can be used to select all attributes of an entity. However, if one wants to select some specific attributes of an entity then one needs to use getRawMany.
As per the documentation -
There are two types of results you can get using select query builder:
entities or raw results. Most of the time, you need to select real
entities from your database, for example, users. For this purpose, you
use getOne and getMany. But sometimes you need to select some specific
data, let's say the sum of all user photos. This data is not an
entity, it's called raw data. To get raw data, you use getRawOne and
getRawMany
From this, we can conclude that the query which you want to generate can not be made using getMany method.

OrientDB SQL query to emulate a many to many join

Given the following schema created using the OrientDB Document API:
OClass team = getoDocDatabase().getMetadata().getSchema().createClass(TEAM);
team.createProperty(NAME, OType.STRING);
OClass driver = getoDocDatabase().getMetadata().getSchema().createClass(DRIVER);
driver.createProperty(NAME, OType.STRING);
OClass car = getoDocDatabase().getMetadata().getSchema().createClass(CAR);
car.createProperty(NAME, OType.STRING);
// Relationships
team.createProperty(CARS_HERITAGE, OType.LINKSET, car);
car.createProperty(BUILT_BY, OType.LINK, team);
car.createProperty(DRIVEN_BY, OType.LINKSET, driver);
driver.createProperty(DRIVER_OF, OType.LINKSET, car);
What's the sql query to fetch all the teams that Fernando Alonso has driven for?
In relational SQL would be as easy as
SELECT team.name FROM {the join} where driver.name = 'Fernando Alonso'
I have try with this db
create class Team
CREATE PROPERTY Team.name String
create class DRIVER
CREATE PROPERTY DRIVER.name String
create class Car
CREATE PROPERTY Car.name String
CREATE PROPERTY Team.CARS_HERITAGE LINKSET Car
CREATE PROPERTY Car.BUILT_BY LINK Team
CREATE PROPERTY Car.DRIVEN_BY LINKSET DRIVER
CREATE PROPERTY DRIVER.DRIVER_OF LINKSET Car
INSERT
INSERT INTO TEAM(name) values ("Ferrari"),("Renault") // Ferrari 12:0 Renault 12:1
insert into Driver(name) values ("Fernando Alonso"),("Giancarlo Fisichella") // Alonso 13:0 Fisichella 13:1
insert into car(name,BUILT_BY,DRIVEN_BY) values ("car ferrari",#12:0,[#13:0,#13:1])
insert into car(name,BUILT_BY,DRIVEN_BY) values ("car renault",#12:1,[#13:0])
Query
select BUILT_BY.name as TeamName from car where DRIVEN_BY.name contains "Fernando Alonso"
Hope it helps.
UPDATE 1
select distinct(BUILT_BY.name) as team from car where DRIVEN_BY.name contains "Fernando Alonso"
FROM JAVA API
UPDATE 2
FROM JAVA API
The answer from #Alessandro is correct, however I've found some weirdnesses in the way the sql is interpreted. Let me explain myself.
I've simplified the goal, let's try to find the query to fetch the teams which have had at least a car.
This first query works, is the one suggested by Alessandro. It returns a list of documents containing one property, that is the name of the team.
select distinct(team.name) as name from Car
This second query works as well, returning the list of teams (as documents).
select expand(distinct(team)) from Car
This third query works and returns exactly the same result that the previous, so it ignores the ".name" part of the select.
select expand(distinct(team)).name from Car
This last query fails. Well it doesn't fail, but it doesn't return what I expected, it returns a list of links to the teams.
select distinct(team).name from Car
Tests running the queries: Tests.

Limit models to select

I have a database table called Event which in CakePHP has its relationships coded to like so:
var $belongsTo = array('Sport');
var $hasOne = array('Result', 'Point', 'Writeup', 'Timetable', 'Photo');
Now am doing a query and only want to pull out Sport, Point, and Timetable
Which would result in me retrieving Sports, Events, Points, and Timetable.
Reason for not pulling everything is due the results having 17000+ rows.
Is there a way to only select those tables using:
$this->Event->find('all');
I have had a look at the API but can't see how its done.
You should set recursive to -1 in your app_model and only pull the things you require. never use recursive of 2 and http://book.cakephp.org/view/1323/Containable is awesome.
just $this->Event->find('all', array('contain' => array()));
if you do the trick of recursive as -1 in app_model, this is not needed, if would just be find('all') like you have

Bug in Kohana 3 ORM?

Sorry to ask all these questions about Kohana. They usually get ignored. I think I just found a bug. I'm making a join between two tables that are not directly related.
$results = ORM::factory('foo')->join("bar")->on("foo.foreign_id", "=", "bar.id");
This generates a query that does not resolve the table names explicitly:
SELECT * FROM `foo` JOIN `bar` ON (`foo`.`foreign_id` = `bar`.`id`)
Which gives (in phpMyAdmin) a table that looks like this:
id time foreign_id blah_int id baz
4 1291851245 3 0 3 52501504
Notice there are two id columns, one for the foo table and one for bar. This is a real problem. Because now, in my results, if I loop through...
foreach ($results as $result) {
echo $result->id; // prints 3!!!
}
Because my results should be foo objects, I expect to get an id of 4, but it's giving me 3 because of the join. Is this a bug in the ORM library? Should I be using a different method to restrict my results from the query? I really don't want to do two separate queries where I load all the bars id's, and then load my foos that way, but it looks like I have to.
You have to use the Database object to build raw queries, not ORM, like this:
$results = DB::select()->from('foo')->join('bar')->on("foo.foreign_id", "=", "bar.id")->execute();
You will need to specific some column aliases however to make your query work unless you use ORM as it was intended.
Using ORM
If you want to use ORM, you need to define the relationships in your model. You mention that they share a relationship with another table so in your case you could use a has many through relationship like this:
protected $_has_many = array(
'bars' => array('model' => 'bar', 'through' => 'other_table', 'foreign_key' => 'foreign_id'),
);
Although your example as given suggests that a straight has_many relationship would work:
protected $_has_many = array(
'bars' => array('model' => 'bar','foreign_key' => 'foreign_id'),
);
This would allow you to access all of the bars using a statement like
$bars = $results->bars->find_all();
foreach($bars as $bar)
{
echo $bar->id; // should echo 4, assuming one record in bars with id 4
}
The Kohana 3.1 ORM Reference Guide is good place to start if you want to learn more about ORM and relationships
Using the Kohana database object and query builder
If you prefer ad hoc queries and are doing joins using the query builder you will likely have colliding column names regardless if you are using Kohana or just raw queries (pop "SELECT * FROM foo JOIN bar ON (foo.foreign_id = bar.id)" into MySQL and you will get the exact same result).
Kohana, just like MySQL allows you to define column aliases for precisely this reason. (See here for more information)
Rewrite your query as follows:
$results = DB::select('id', 'time', 'foreign_id', array('bar.id', 'bar_id'), 'baz')->from('foo')->join("bar")->on("foo.foreign_id", "=", "bar.id")->execute();
This will return:
id time foreign_id blah_int bar_id baz
4 1291851245 3 0 3 52501504

Speed Performance In Recursive SQL Requests

I have so category and this categories have unlimited sub category.
In Database Table, Fields are ID, UpperID and Title.
If I call a category and its subcategory in DataTable with recursive method in program(ASP.NET project)
performance is very bad.
And many user will use this application so everything goes bad.
Maybe All categories Fill to A Cache object and then we musnt go to Database.
But category count is 15000 or 20000.
So I think isn't a good method.
What can I do for fast performance?
Are you give me any suggestion?
caching or other in-memory-persistance is by far better than doing this on a relational system :) ... hey... it's oop!
just my 2 cents!
eg.
var categories = /* method for domain-objects*/.ToDictionary(category => category.ID);
foreach (var category in categories.Values)
{
if (!category.ParentCategoryID.HasValue)
{
continue;
}
Category parentCategory;
if (categories.TryGetValue(category.ParentCategoryID.Value, out parentCategory))
{
parentCategory.AddSubCategory(category);
}
}
et voila ... your tree is ready to go!
edit:
do you exactly know where your performance bottle-neck is?...
to give you some ideas, eg:
loading from database
building up the structure
querying the structure
loading from database:
then you should load it once and be sure to have some changetracking/notifying to get changes (if made) or optimize your query!
building up the structure:
the way i create the tree (traversal part) is the wastest you can do with a Dictionary<TKey, TValue>
querying the structure:
the structure i've used in my example is faster than List<T>. Dictionary<TKey, TValue> uses an index over the keys - so you may use int for the keys (IDs)
edit:
So you use DataTable to fix the
problem. Now you've got 2 problems: me
and DataTable
what do you have right now? where are you starting from? can you determine where your mudhole is? give us code!
Thanks All,
I find my solution with Common Table Expressions(CTE) fifty- fifty.
Its allow fast recursive queries.
WITH CatCTE(OID, Name, ParentID)
AS
(
SELECT OID, Name, ParentID FROM Work.dbo.eaCategory
WHERE OID = 0
UNION ALL
SELECT C.OID, C.Name, C.ParentID FROM Work.dbo.eaCategory C JOIN CatCTE as CTE ON C.ParentID= CTE.OID
)
SELECT * FROM CatCTE