find query for many to many relation propel

前端 未结 1 932
攒了一身酷
攒了一身酷 2021-01-16 05:11

i am new for propel . i face a problem to fetch all record form both table which have many to many relation .

i have a user and group table. and a join table us

相关标签:
1条回答
  • 2021-01-16 05:55

    You cannot join a many-to-many relation directly since there is no such thing in MySQL. You can do one of two things...

    If you have a User object already, then you can simply "get" the related Groups this way:

    $relatedGroups = $userObject->getGroups();
    

    If you don't have a User object yet, and you want to populate all records (users and groups), then I think you could do this:

    $users = UserQuery::create()
               ->join('User.UserGroup')
               ->join('UserGroup.Group')
               ->with('Group')  // this line hydrates Group objects as well as Users
               ->find();
    

    Now in your code you can loop through Users and get each one's Groups without an extra DB hit:

    foreach ($users as $user) {
      $user->getGroups();
      // normally this would be an extra DB hit, but because we used "->with('Group')"
      // above in the query, the objects are already hydrated.
    }
    

    Hope this helps. There is info on minimizing queries using "with()" on the Propel site as well info on many-to-many relationships (with query examples).

    0 讨论(0)
提交回复
热议问题