Cakephp 3 queryBuilder for many to many relations - cakephp

I have a query which i am executing directly using connection manager like
$connection = ConnectionManager::get('default');
$sizes = $connection->execute('SELECT s.name size_name, s.id size_id, tp.price
FROM toppings t
INNER JOIN `sizes` s on s.category_id = t.category_id
LEFT JOIN `toppings_prices` tp ON tp.topping_id = t.id AND tp.size_id = s.id
WHERE t.id= :id', ['id' => $id])->fetchAll('assoc');
In this case Sizes and Toppings have many to many relation and the assocaitions are defined as per CakePHP 3 docu like in ToppingTable i have defined the relation like
$this->belongsToMany('Sizes', [
'foreignKey' => 'topping_id',
'targetForeignKey' => 'size_id',
'joinTable' => 'toppings_prices'
]);
The above query is defined in ToppingsController's edit method.
Is there are better way to acive the same results as from the above query?
I have tried CakePHP standards like, which return all possible fields from all 3 tables which I actually don't want
$rs = $this->Toppings
->find()
->contain(['Sizes'])
->where(['category_id' => $categoryId]);

Related

Subquerys in cakephp 3.x, new ORM?

I'm new in Cakephp 3.x and I'm having some trouble to create a subquery in the new ORM format. I have this report in my application, that needs to return the follow result:
1. There are three entities - Users, Calls, CallStatus.
2. Users hasMany Calls, Calls hasMany CallStatus.
3. I need to count how many CallStatus each user has in Calls.
Now follow the query that I need to put on new ORM format:
SELECT U.name,
(SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =1 and C.user_id=U.id) AS 'Unavailable',
(SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =2 and C.user_id=U.id) AS 'Busy',
(SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =3 and C.user_id=U.id) AS 'Contacted',
(SELECT COUNT(*) FROM calls as C WHERE C.call_status_id =4 and C.user_id=U.id) AS 'Error'
FROM `users` AS U
WHERE U.profile=3 and U.is_active=1
Could someone give me a help, please? Thanks
If I understand you correctly, you want to see the number of calls for every callstatus you have for a specific user.
Try the following. Note that I used the CakePHP convention for naming the callstatuses (which is plural).
// get the tableregistry
use Cake\ORM\TableRegistry;
$callstatuses = Cake\ORM\TableRegistry::get('Callstatuses');
// for user with id 2, get the number of calls for each callstatus
$callstatuses->find()
->contain(['Calls'])
->where(['Calls.user_id' => 2, 'User.is_active' => 1])
->countBy('name')
->toArray();
// output could be:
//[ 'Unavailable' => 2, 'Busy' => 1 ]
You can find information about creating queries in the CakePHP book: see 'Query Builder'.
If you want to know more about working with/on queries, note that queries are Collections. Anything you can do on a Collection object, you can also do in a Query object. See the Collection section in the CakePHP book.
You have to use subqueries, as many as you want!
Here is an example for your case:
$q = $this->Calls->find();
$q1->select([$q->func()->count('*')])
->where(['Calls.user_id = Users.id', 'call_status_id' => 1]);
$q2->select([$q->func()->count('*')])
->where(['Calls.user_id = Users.id', 'call_status_id' => 2]);
$q3->select([$q->func()->count('*')])
->where(['Calls.user_id = Users.id', 'call_status_id' => 3]);
$q4->select([$q->func()->count('*')])
->where(['Calls.user_id = Users.id', 'call_status_id' => 4]);
$qUsers = $this->Users->find()
->select([
'id',
'first_name',
'Unavailable' => $q1,
'Busy' => $q2,
'Contacted' => $q3,
'Error' => $q4
])
->where(['profile' => 3, 'active' => 1])
->all();
Note: That nicer if you use a loop to create suqueries in this case.

cakephp: find ignores DISTINCT

i got the following cakephp find situation:
$data = $this->find('all', array(
'conditions' => array(
'Roster.league_id' => $league_id,
'Roster.season' => $season,
),
'fields' => array(
'DISTINCT Roster.player_id',
'Roster.league_id',
'Roster.fflteam_id',
'Roster.season',
'Roster.modified',
'Fflteam.name',
'Player.firstName',
'Player.lastName',
'Player.position'
),
'order' => array(
'Roster.player_id',
'Roster.modified DESC'),
'contain' => array(
'Fflteam',
'Player' => array(
'Stat' => array(
'conditions' => array(
'Stat.season' => $season),
'Scores'),
'Teamplayer')
)
));
There are more Roster-records with specific player_ids, thats why i try to use DISTINCT. I only need the most recent. Thats why i order the results by player_id and Roster.modified. But die DISTINCT command gets ignored.
e.g:
records:
id=1 player_id=1 modified=2012
id=2 player_id=1 modified=2013
id=3 player_id=1 modified=2014
id=4 player_id=2 modified=2014
id=5 player_id=2 modified=2013
result should be:
id=3 player_id=1 modified=2014
id=4 player_id=2 modified=2014
I don't see any syntax errors. Maybe there some commands are not possible together or my way of filtering is wrong. would be great if someone can help me.
DISTINCT does not give you one distinct field if there are multiple fields , if you have Distinct title it will provides distinct title .
If you have distinct id , title it will output distinct combination of rows with same id and title.
This is how DISTINCT works.
Try GroupBy
Check this page to understand what to use when http://www.mysqltutorial.org/mysql-distinct.aspx
As AgRizzo suggested i am using a query now.
Its split into 2 Parts. The first gets all entries with the one2one relations:
$this->query("SELECT *
FROM (SELECT * FROM `rosters` AS `Roster1` WHERE " . $conditions . " ORDER BY `Roster1`.`modified` DESC) AS `Roster`
LEFT JOIN `fflteams` AS `Fflteam` ON (`Roster`.`fflteam_id` = `Fflteam`.`id`)
LEFT JOIN `players` AS `Player` ON (`Roster`.`player_id` = `Player`.`id`)
GROUP BY `Player`.`id` ORDER BY `Roster`.`player_id` ASC");
The second part gets all one2many relations with its relation:
$this->Stat->find('all', array(
'conditions' => $conditions,
'contain' => array(
'Scores')
));
at the end i merge those 2 arrays

CakePHP find joined records with conditions on each table

I want to see all the records from a join, setting a WHERE condition on each side of the join.
For example, I have LOAN and BORROWER (joined on borrower.id = loan.borrower_id). I want the records where LOAN.field = 123 and BORROWER.field = 'abc'.
The answers here (this one, for example) seem to say that I should use Containable.
I tried that. Here's my code:
$stuff = $this->Borrower->find('all', array(
'conditions' => array(
'Borrower.email LIKE' => $this->request->data['email'] // 'abc'
),
'contain'=>array(
'Loan' => array(
'conditions' => array('Loan.id' => $this->request->data['loanNumber']) // 123
)
)
));
I expected to have a single result because in my data, there is only one joined record with both of those conditions. Instead, I get two results,
Result 1 is {Borrower: {field:abc, LOAN: {field: 123} } // correct
Result 2 is {Borrower: {field:abc, LOAN: {NULL} } // incorrect
When I look at the SQL that CakePHP used, I don't see a join. What I see is two separate queries:
Query 1: SELECT * from BORROWER // (yielding 2 IDs),
Query 2: SELECT * FROM LOAN WHERE borrower_id in (IDs)
This is not what I want. I want to join the tables, then apply my conditions. I could easily write the SQL query, but am trying to do it the Cake way since we've adopted that framework.
Is it possible?
Try to do something like this:
$options['conditions'] = array(
'Borrower.email LIKE' => $this->request->data['email'] // 'abc',
'loan.field' => '123' )
$options['joins'] = array(
array('table' => 'loans',
'alias' => 'loan',
'type' => 'INNER',
'conditions' => array(
'borrower.id = loan.borrower_id')
)
);
$options['fields'] = array('borrower.email', 'loan.field');
$test = $this->Borrower->find('all', $options);
You should see a SQL statement like:
SELECT borrower.email, loan.field
FROM borrowers AS borrower
INNER JOIN loans AS loan
ON borrower.id = loan.borrower_id
AND loan.field = '123'
WHERE borrower.email = 'abc'
Your results will be in an array
{Borrower: {field:abc} LOAN: {field: 123} }
You will find more information in this document.
I think I'll accept Jose's answer because it's exactly what I want. But I did notice that I didn't need any fancy tricks -- no joins or contains -- if I used the other model as my starting point.
A Borrower hasMany Loans, and a Loan belongsTo a Borrower. Using Loan as my model, Cake will automatically join the tables, but not using Borrower.
$this->Loan->find('all', array( // Not $this->Borrower->find() !
'conditions' => array(
'Borrower.field' => 'abc',
'Loan.field' => 123
)
));

Paginate results filtered by condition on associated model (HABTM) using Containable

I need to paginate list of Products belonging to specific Category (HABTM association).
In my Product model I have
var $actsAs = array('Containable');
var $hasAndBelongsToMany = array(
'Category' => array(
'joinTable' => 'products_categories'
)
);
And in ProductsController
$this->paginate = array(
'limit' => 20,
'order' => array('Product.name' => 'ASC'),
'contain' => array(
'Category' => array(
'conditions' => array(
'Category.id' => 3
)
)
)
);
$this->set('products', $this->paginate());
However, resulting SQL looks like this:
SELECT COUNT(*) AS `count`
FROM `products` AS `Product`
WHERE 1 = 1;
SELECT `Product`.`*`
FROM `products` AS `Product`
WHERE 1 = 1
ORDER BY `Product`.`name` ASC
LIMIT 20;
SELECT `Category`.`*`, `ProductsCategory`.`category_id`, `ProductsCategory`.`product_id`
FROM `categories` AS `Category`
JOIN `products_categories` AS `ProductsCategory` ON (`ProductsCategory`.`product_id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) AND `ProductsCategory`.`category_id` = `Category`.`id`)
WHERE `Category`.`id` = 3
(I.e. it selects 20 Products and then queries their Categories)
while I'd need
SELECT COUNT(*) AS `count`
FROM `products` AS `Product`
JOIN `products_categories` AS `ProductsCategory` ON `ProductsCategory`.`product_id` = `Product`.`id`
JOIN `categories` AS `Category` ON `Category`.`id` = `ProductsCategory`.`category_id`
WHERE `Category`.`id` = 3;
SELECT `Product`.*, `Category`.*
FROM `products` AS `Product`
JOIN `products_categories` AS `ProductsCategory` ON `ProductsCategory`.`product_id` = `Product`.`id`
JOIN `categories` AS `Category` ON `Category`.`id` = `ProductsCategory`.`category_id`
WHERE `Category`.`id` = 3
ORDER BY `Product`.`name` ASC
LIMIT 20;
(I.e. select top 20 Products which belong to Category with id = 3)
Note:
Possible solution without Containable would be (as Dave suggested) using joins.
This post offers a very handy helper to build $this->paginate['joins'] to paginate over HABTM association.
Note: Still looking for more elegant solution using Containable than fake hasOne binding.
Finally I found a way to do what I want, so posting it as an answer:
To force JOIN (and be able to filter via condition on associated model) in Containable - you've got to use fake hasOne association.
In my case, code in ProductsController should be:
$this->Product->bindModel(array('hasOne' => array('ProductsCategory')), false);
$this->paginate = array(
'limit' => 20,
'order' => array('Product.name' => 'ASC'),
'conditions' => array(
'ProductsCategory.category_id' => $category
),
'contain' => 'ProductsCategory'
);
$this->set('products', $this->paginate());
Note false as a second argument to bindModel - which makes binding persistent. This is needed because paginate() issues find('count') before find('all'), which would reset temporary binding. So you might want to manually unbindModel afterwards.
Also, if your condition includes multiple IDs in HABTM associated model, you might want to add 'group' => 'Product.id' into your $this->paginate[] (as Aziz has shown in his answer) to eliminate duplicate entries (will work on MySQL only).
UPDATE:
However, this approach has one serious drawback compared to joins approach (suggested by Dave): condition can apply only to intermediate model's foreign key (category_id in my case); if you want to use condition on any other field in associated model - you'd probably have to add another bindModel('hasOne'), binding intermediate model to HABTM associated model.
When you put the condition in the nested Contain, you're asking it to retrieve only the Categories with that ID. So - it's doing what you're asking, but that's not what you want.
Though it seems like it should be possible, the only luck I've had doing what you're trying to do (after MANY hours and a few stackoverflow questions) is via Joins instead of Contain.
http://book.cakephp.org/view/1047/Joining-tables
It's not the exact same problem, but you can go through some of my code where I query against HABTM conditions (I answered my question at the bottom) here: Select All Events with Event->Schedule->Date between start and end dates in CakePHP

CakePHP 3 find() with beforeFind() callback SQL issue

I'm having a problem with data integrity when using find() in my controller in conjunction with beforeFind() in a behavior callback. The WHERE Submissions.site_id is not being added in the WHERE clause like it should be. I get different result sets depending on where the WHERE clause is set.
in my SubmissionsController:
public function index()
{
$query = $this->Submissions->find('all')
->where(['user_id' => $this->Auth->user('id')])
->contain(['Users', 'Categories']);
$this->set('submissions', $this->paginate($query));
}
In my beforeFind() Model callback (attached as a 'TenantBehavior' to
$query->where([$this->_table->alias().'.'.'site_id' => 3]);
The problem is that with the above, the SQL generated puts the "WHERE" clause as an AND on the JOIN condition like so, and NOT on the actual WHERE:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
user_id = 315
If I remove the beforeFind() ->where and instead place it on the controller ->where I get the expected SQL and result set like so:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
(
user_id = 315
AND Submissions.site_id = 3
)
Thoughts? Suggestions?
EDIT
As #ndm's suggestion, I began to update and provide much more context. In doing so I discovered (like an idiot) that I was missing the $this->addBehavior('Tenant'); on my 'SubmissionsTable' model. Adding this of course solved the issue.
$query = $this->Submissions->find('all', [
'conditions' => [
'user_id' => $this->Auth->user('id')
],
'contain' => [
'Users',
'Categories',
]
]);
Passing conditions as inline array will solve your issue and append beforeFind() where conditions properly.

Resources