Let’s say I have a schema where User has many Alerts (many to many).
Alert:
columns: ~
User:
columns: ~
relations:
Alerts:
class: Alert
refClass: UserAlert
local: user_id
foreign: alert_id
UserAlert:
columns:
user_id:
type: integer(4)
primary: true
alert_id:
type: integer(4)
primary: true
active:
type: boolean
notnull: true
default: true
relations:
Alert:
local: alert_id
foreign: id
User:
local: user_id
foreign: id
Notice a custom active field in the ref class which tells if related alert is active for the user. How do I fetch a user with his active alerts?
UPDATE:
One way to achieve this is to override join condition with WITH keyword:
$user = UserTable::createQuery('u')
->createQuery('u')
->leftJoin('u.UserAlert aa WITH aa.enabled = ?', array(true))
->leftJoin('aa.Alert a')
->addWhere('u.id = ?', $id)
->fetchOne();
But this way you would have to call $user->getUserAlert() which returns a collection of ref class objects. I would like to have a ‘alerts’ relation populated, so that I could call $user->getAlerts() directly.
First, your schema is wrong (at least, it doesn’t work on my side). Here is the correct one (I put some field in User and Alert for test):
You have to define your many2many realtion in both Alert, User and UserAlert.
Then I build the db and put some data inside, for the test: http://sqlfiddle.com/#!2/dd507/2
Now, to retrieve all users with only their active alerts, put this in your UserTable.php
And then, in your action, simply do that:
If you
print_ryour results, you will see that we retrieve users3and4with their active alerts: