I encountered a problem to write this query in a Yii model oriented style.
I have a 3 main tables : questions, categories, countries
and relational tables : questions_has_categories, questions_has_countries.
Now i try to search questions that belongs to country, category.
With normal SQL statement i write :
SELECT q.id, q.question, c.name, co.name
FROM questions AS q,
categories AS c,
countries AS co,
questions_has_countries AS ta,
questions_has_categories AS qhc
WHERE
q.id = qhc.questions_id
AND c.id = qhc.categories_id
AND q.id = ta.questions_id
AND co.id = ta.countries_id
AND c.id = 1
AND co.id = 2
This works fine.
Now with Yii Active Record i try to search like this :
$model = Questions::model()->with(
array( 'categories' => array (
'select' => 'name',
'condition' => 'categories.id=:cat_id',
'params' => array (':cat_id' => $_POST["Questions"]["categories"])
)
),
array( 'countries' => array (
'select' => 'name',
'condition' => 'countries.id=:cou_id',
'params' => array (':cou_id' => $_POST["Questions"]["countries"])
)
)
)->findAll(array ('select' => 'question'));
This code respects only the categories, not countries ( returns for all countries, doesnt filter, narrow down ).
What am i doing wrong ?
My Question Model relations function looks like this :
public function relations()
{
return array('categories' => array(self::MANY_MANY, 'Categories', 'questions_has_categories(questions_id, categories_id)'),
'countries' => array(self::MANY_MANY, 'Countries', 'questions_has_countries(questions_id, countries_id)'),
);
}
Pls help :)
Thanks
try this
$model = Questions::model()->with(
array( 'categories' => array (
'select' => 'name',
'condition' => 'categories.id=:cat_id',
'params' => array (':cat_id' => $_POST["Questions"]["categories"])
),
'countries' => array (
'select' => 'name',
'condition' => 'countries.id=:cou_id',
'params' => array (':cou_id' => $_POST["Questions"]["countries"])
)
)
)->findAll(array ('select' => 'question'));
Related
I am building an application using CakePHP and I am stuck on a problem retrieving data using a series of joins. In the simplified example below the join with the alias Delivery could have more than record and I want to bring back the record with a max value in a particular field in that table.
$inv_conditions = array( 'Invoice.invoice_date >=' => $DateFormatter->dateForDB($dateFrom),
'Invoice.invoice_date <=' => $DateFormatter->dateForDB($dateTo),
'Invoice.id >' => 385380 );
$join = array(array(
'table' => 'jobs',
'alias' => 'Jobs',
'type' => 'LEFT',
'conditions' => array('Invoice.job_id = Jobs.JOB_ID' )
),
array(
'table' => 'functional',
'alias' => 'Delivery',
'type' => 'LEFT'
'conditions'=> array('AND ' => array('Invoice.job_id = Delivery.JOB',
'Delivery.TYPE_STAGE = 1')
)
)
);
$invoices = $this->Invoice->find("all", array(
"fields" => array(
'Invoice.id',
'Invoice.job_id',
'Invoice.invoice_no',
'Invoice.consolidated_type',
'Invoice.customer_id_tbc',
'Invoice.invoice_date',
'Invoice.invoice_reference',
'Invoice.invoice_req',
'Jobs.PAYMENT_TYPE',
'Jobs.CUSTOMER',
'Jobs.MOST_RELEVANT_LINE',
'Delivery.DEPARTURE_DATE',
'Delivery.CNOR_CNEE_NAME',
'Delivery.TOWN_NAME',
),
"conditions" => $inv_conditions,
"joins" => $join
)
);
}
I can do this with SQL no problem as follows:
SELECT
jobs.JOB_ID,
jobs.CUSTOMER,
functional.JOB_LINE_ORDER,
functional.CNOR_CNEE_NAME,
functional.TOWN_NAME
FROM jobs JOIN functional ON
jobs.JOB_ID = 'M201409180267'
AND
functional.JOB = jobs.JOB_ID
AND
functional.TYPE_STAGE = 0
AND
functional.JOB_LINE_ORDER =
(SELECT MAX(JOB_LINE_ORDER) FROM functional
WHERE functional.JOB = 'M201409180267' AND functional.TYPE_STAGE = 0)
I have tried using the following to the conditions array:
'conditions' => array('AND ' =>
array( 'Invoice.job_id = Delivery.JOB',
'Delivery.TYPE_STAGE = 1'
'Delivery.JOB_LINE_ORDER = MAXIMUM(Delivery.JOB_LINE_ORDER)' )
)
This does bring back results but not the correct ones and the resulting SQL generated by Cake does have a select in the where clause. Is there a way of doing this when retrieving data in cake where the sql statement created will have a select in the where clause.
Any suggestions would be greatly appreciated.
Thanks
Bas
You need to use subquery to generate the select in the where clause. You can create a method in your model that does this and call it from your controller.
$subQuery = $db->buildStatement(
array(
'fields' => array(''),
'table' => $db->fullTableName($this),
'alias' => 'aliasName',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsArray,
'order' => null,
'group' => null
),
$this
);
$subQuery = ' <<YOUR MAIN QUERY CONDITION (' . $subQuery . ') >>';
$subQueryExpression = $db->expression($subQuery);
$conditions[] = $subQueryExpression;
return $this->Model->find('list', compact('conditions'));
OK, another cake question from me.
I have rather a complex table structure with quite a few joins. Here's the jist of it:
So, in summary:
RiskCategory $hasMany Client [Client $belongsTo RiskCategory]
Client $hasMany Account [Account $belongsTo Client]
Account $hasMany Holding [Holding $belongsTo Account]
In my RiskCategory model I want to run a query that basically returns the sum of the holdings in each riskCategory id, grouped by date. There's a few other conditions but here is what I've put together:
$findParams = array(
'recursive' => 4,
'fields' => array(
'Holding.holding_date',
'SUM(Holding.value) AS risk_category_value'
),
'group' => array('Holding.holding_date'),
'order' => 'Holding.holding_date ASC'
);
$findParams['conditions'] = array(
'Client.active' => true,
'Client.model' => true,
'Client.currency' => 'GBP',
'OR' => array(
'Holding.holding_date' => $this->end_date,
array(
'Holding.holding_date = LAST_DAY(Holding.holding_date)',
'MONTH(Holding.holding_date)' => array(3,6,9,12)
)
)
);
$valuations = $this->Client->Account->Holding->find( 'all', $findParams );
When I run the above cake is giving me an error saying various fields are not present in the query. The raw query created is as follows:
SELECT `Holding`.`holding_date`,
Sum(`Holding`.`value`) AS risk_category_value
FROM `ips_client_db`.`holdings` AS `Holding`
LEFT JOIN `ips_client_db`.`accounts` AS `Account`
ON ( `Holding`.`account_id` = `Account`.`id` )
LEFT JOIN `ips_client_db`.`sedols` AS `Sedol`
ON ( `Holding`.`sedols_id` = `Sedol`.`id` )
WHERE `client`.`active` = '1'
AND `client`.`model` = '1'
AND `client`.`currency` = 'GBP'
AND ( ( `Holding`.`holding_date` = '2013-10-01' )
OR (( ( `Holding`.`holding_date` = Last_day(
`Holding`.`holding_date`) )
AND ( Month(`Holding`.`holding_date`) IN ( 3, 6, 9, 12 ) ) )
) )
GROUP BY `Holding`.`holding_date`
ORDER BY `Holding`.`holding_date` ASC
It looks as though cake is not doing all the joins. It is only joining Account to Holding and then Holding to Sedol (which is another joined table in the database but is not needed for this query so I've omitted it from the diagram)
Why are the joins not being made properly and how to acheive this? I'd like to avoid writing a raw statement if possible.
EDIT: The joins should be as follows:
...
FROM risk_categories
LEFT JOIN ((clients
LEFT JOIN accounts
ON clients.id = accounts.client_id)
LEFT JOIN holdings
ON accounts.id = holdings.account_id)
ON risk_categories.id = clients.risk_category_id
...
CakePHP does not perform deep joins for associations that are more than 1 level deep. That is why you're getting an error for references to the Client table in the conditions.
For these types of problems it's easier to use the Containable behavior. I usually add this behavior to my AppModel as the default handler for associations.
Containable allows you to define the associations (only those already defined) with their fields and conditions as part of the find operation. This is done by adding a new contain key in the find parameters. Below I've taking a guess at what you might need.
$findParams = array(
'fields' => array(
'Holding.holding_date',
'SUM(Holding.value) AS risk_category_value'
),
'conditions'=>array(
'OR' => array(
'Holding.holding_date' => $this->end_date,
array(
'Holding.holding_date = LAST_DAY(Holding.holding_date)',
'MONTH(Holding.holding_date)' => array(3,6,9,12)
)
)
),
'group' => array('Holding.holding_date'),
'order' => 'Holding.holding_date ASC',
'contain'=>array(
'Account'=>array(
'Client'=>array(
'RiskCategory',
'conditions'=>array(
'Client.active' => true,
'Client.model' => true,
'Client.currency' => 'GBP',
)
)
)
)
);
$valuations = $this->Client->Account->Holding->find( 'all', $findParams );
So, I have three tables. Movies, movies_genres and genres. I want to get a movie by its Id, and also join its genres in the result. I managed to join the results, but it doesn't display as i want it to. I'm not sure if what I'm asking is possible.
This is my query:
SELECT `movies`.*, GROUP_CONCAT(genres.id) AS genre_id, GROUP_CONCAT(genres.name) AS genre_name
FROM (`movies`)
INNER JOIN `movies_genres`
ON `movies_genres`.`movie_id` = `movies`.`id`
INNER JOIN `genres`
ON `genres`.`id` = `movies_genres`.`genre_id` WHERE `movies`.`id` = 19908
GROUP BY `movies`.`id`
The query was generated by Codeigniters Active Record class, here is the Codeigniter code if that helps:
$this->db->select('movies.*, GROUP_CONCAT(genres.id) AS genre_id, GROUP_CONCAT(genres.name) AS genre_name');
$this->db->from('movies');
$this->db->where('movies.id', $movie_id);
$this->db->join('movies_genres', 'movies_genres.movie_id = movies.id', 'inner');
$this->db->join('genres', 'genres.id = movies_genres.genre_id', 'inner');
$this->db->group_by('movies.id');
Here is the result i'm currently getting:
Array
(
[id] => 19908
[movie_title] => Zombieland
[overview] => An easily spooked guy...
[genre_id] => 28,12,35,27
[genre_name] => Action,Adventure,Comedy,Horror
)
And this is what I want:
Array
(
[id] => 19908
[movie_title] => Zombieland
[overview] => An easily spooked guy...
[genres] => array(
0 => array(
'id' => 28,
'name' => Action
),
1 => array(
'id' => 12,
'name' => Adventure
),
1 => array(
'id' => 35,
'name' => Comedy
),
1 => array(
'id' => 27,
'name' => Horror
)
)
)
Is this possible, and if so, how?
The query you listed will have n rows (where n = # of movies) whereas the query it seems you want will have many more rows (# of movie_genre's entries). You're probably better off leaving that query as it is, and doing some post processing.
Consider:
After you get it, just run your result (e.g. $result) array through something like:
foreach($result as &$row)
{
// Split over commas
$gi_elements = explode(',', $row['genre_id']);
$gn_elements = explode(',', $row['genre_name']);
// Build genre
$row['genre'] = array();
for($i=0; $i<count($gi_elements); $i++)
{
$row['genre'][] = array('id' => $gi_elements[$i], 'name' => $gn_elements[$i]);
}
// Cleanup
unset($row['genre_id']);
unset($row['genre_name']);
}
Afterwards, $results will look exactly as you wish without extra database work.
EDIT: Fixed some typos.
How do I use DISTINCT to get unique user id with highest value for total_time_driven_at_this_trip and also pull user_name from another table which has belongsto relations based on user_id?
I tried this...
$this->set('tripNsws', $this->TripNsw->find('all',array('limit' => 20,'fields' => array('DISTINCT(TripNsw.user_id)','TripNsw.total_time_driven_at_this_trip'),'group' => array('TripNsw.user_id') ,'order' => array('TripNsw.total_time_driven_at_this_trip desc'))));
but it's not working.
I suppose you need to get below....
SELECT DISTINCT(user_id),`total_time_driven_at_this_trip` FROM `trip_nsws` order by `total_time_driven_at_this_trip` desc
// see below url
http://book.cakephp.org/1.3/view/1018/find
array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'recursive' => 1, //int
'fields' => array('Model.field1', 'DISTINCT Model.field2'), //array of field names
'order' => array('Model.created', 'Model.field3 DESC'), //string or array defining order
'group' => array('Model.field'), //fields to GROUP BY
'limit' => n, //int
'page' => n, //int
'offset'=>n, //int
'callbacks' => true //other possible values are false, 'before', 'after'
)
// or try this
function some_function() {
$total = $this->Article->find('count');
$pending = $this->Article->find('count', array('conditions' => array('Article.status' => 'pending')));
$authors = $this->Article->User->find('count');
$publishedAuthors = $this->Article->find('count', array(
'fields' => 'DISTINCT Article.user_id',
'conditions' => array('Article.status !=' => 'pending')
));
}
Correct Syntax for DISTINCT keywork in cakephp
$this->set('banners', $this->Banner->find('all',array('fields'=>'DISTINCT Banner.id')));
Make sure DISTINCT uses in fields array.
The correct syntaxis is
$this->set('tripNsws', $this->TripNsw->find('all',array('fields'=>'DISTINCT TripNsw.user_id')));
I've always used a GROUP BY in the query to get the same result as DISTINCT
You can consider setting it as a Virtual Field ( http://book.cakephp.org/1.3/view/1608/Virtual-fields )
$this->Model->virtualFields['distinct_user'] = 'DISTINCT Model.user_id';
'fields' => array('DISTINCT Model.Modelfield')
or
'fields' => array('Model.id','DISTINCT Model.Modelfield')
I apologize for the horrible title, I couldn't think of how to explain my problem.
In my database I have the following tables, articles, tags, and articles_tags. An article can have many tags.
Currently I am able to grab all the articles, with all the tags, but I want to be able to find articles based upon it's tags.
My select is simple:
$articles = $this->Article->find('all', array(
// extra condition to check for tag, maybe?
'conditions' => array('Article.status' => 'active'),
'limit' => $this->articles_per_page,
'offset' => ($page_num-1)*$this->articles_per_page
));
My return from the database is as follows:
Array
(
[0] => Array
(
[Article] => Array
(
[id] => 1
)
[Tag] => Array
(
[0] => Array
(
[id] => 1
[name] => Ruby
[slug] => ruby
[uses] => 1
[ArticlesTag] => Array
(
[id] => 1
[article_id] => 1
[tag_id] => 1
)
)
)
)
What do I do if I only want to return the articles with a Ruby tag?
Try this
// In your Article model
function getArticleByTagSql($tag)
{
$dbo = $this->getDataSource();
$subQuery = $dbo->buildStatement(
array(
'fields' => array('DISTINCT(ArticlesTag.article_id)'),
'table' => "articles_tags",
'joins' => array(
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'INNER',
'conditions' => array('ArticlesTag.tag_id = Tag.id')
)
),
'alias'=>"ArticlesTag",
'conditions' => array("Tag.name"=>Sanitize::clean($tag_words)),
'order' => null,
'group' => "ArticlesTag.article_id"
),
$this
);
$subQuery = ' Article.id IN (' . $subQuery . ')';
return $dbo->expression($subQuery);
}
// In your Articles Controller
$this->paginate['conditions'][] = $this->Article->getArticleByTagSql($tag_name);
$this->paginate['conditions'][] = array('Article.status' => 'active');
$this->paginate['limit'] = $this->articles_per_page;
// or as per your example
$articles = $this->Article->find('all', array(
// extra condition to check for tag, maybe?
'conditions' => array('Article.status' => 'active',$this->Article->getArticleByTagSql($tag_name)),
'limit' => $this->articles_per_page,
'offset' => ($page_num-1)*$this->articles_per_page
));
For conditions like this you can use the LinkableBehavior. It's designed for exact your wanted result. In case you don't want to use it, you have to do a query on the tag controller:
$this->Tag->find('all', array('conditions' => array('Tag.name' => 'ruby')));
Not possible directly.
The easiest way is to make the query through the tag controller
I'm updating this question with an answer for CakePHP 3.x.
You can find all articles for a given tag using an INNER JOIN. The benefit of this join is that it keeps articles as the primary table in the query. Making this an easy solution when you're paginating results by a HABTM join.
$tag_id = 3; // the ID of the tag
$query = $this->Articles->find('all')
->innerJoin('articles_tags', [
'Articles.id = articles_tags.article_id',
'articles_tags.tag_id' => $tag_id
]);
The first join condition has to be the array key. If you use a => array assignment then CakePHP will pass the articles_tags.article_id as a string argument to the join condition. Which won't work.
You can also stack innerJoin for multiple HABTM conditions. For example; find all articles for a tag and also for a category. You can also use the in query expression to match multiple tags.
You can also use the above in pagination like this $articles = $this->paginate($query);
I'm sure this information is out on the web, but this question was the top of google's results. So maybe this will help others.