Reputation: 417
Problem in short: I want to set conditions on an associated model. How do I do it?
I'm having a problem with the associations in my CakePHP application.
The associations looks like this:
Event has many EventSum belongs to Account has many AccountUser belongs to User
Event has many EventDebt ... (the rest is the same as above)
Event also belongs to User
The application is a private econonmy program in PHP and uses the CakePHP framework.
An Event is a financial event, a purchase, transaction between accounts etc. It only holds information about date, title and user.
An EventSum holds information about an Account and how much to debit or credit (in one column, just positive or negative).
Account holds information about title of the account.
AccountUser holds an id of an Account and a User. This indicates that
So, now I want to fetch Events based on what accounts a User is associated to. How can I do this?
I want to fetch the following info: Event, together with the EventSum. The Events are fetched from Accounts where the User has access.
Thanks for any help, /Magnus
Upvotes: 1
Views: 1889
Reputation: 776
It seems like you want to be able to query your Event
class with the following conditions:
'Account.user_id =' => $userId
Is my assumption correct?
When doing queries which require conditions on associated models, you can use either the Containable
behaviour (comes with CakePHP 1.3) or the 'Linkable' behaviour (which can be found here).
What happens when you try this (be sure to attach the Containable
behaviour to your models first):
$condition = array('Account.user_id =' => $userId);
$contain = array('EventSum' => array('Account'), 'EventDebt' => array('Account'));
$result = $this->Event->find('all', compact('condition', 'contain'));
Note that you might experience issues when 'containing' both EventSum
and EventDebt
if both of their associations to Account
use the same alias name.
Upvotes: 1