0

I'm using Propel ORM v2 to retrieve records from a table which is linked to records of another table using foreign key. I'd like to return only certain fields from both the parent table and the child table.

What is the best way to do this?

My table structure looks like this:

Table: User
- Id
- Name
- Age
- MaritalStatus
Table: Profile
- UserId (FK->User.Id)
- Street
- City
- State
- Country
- TelephoneNumber

I have tried the following but the query does not return the desired User object with children Profile objects and only the selected fields of Id, Name for the User object and TelephoneNumber for the Profile child objects:

\UserQuery()::create
->select(array('Id', 'Name', 'Profile.Telephonenumber'))
->leftJoinWithProfile()
->find()
->toArray();

Any advise is greatly appreciated

EthanS
  • 734
  • 1
  • 5
  • 8

2 Answers2

0

just took a quick look over Propel.

  1. This select returns what you have asked for, ('Id', 'Name', 'Profile.Telephonenumber').

    \UserQuery::create() ->join('Profile') ->select(array('Id', 'Name', 'Profile.Telephonenumber')) ->find() ->toArray();

    //returns an array with values for 'Id','Name', 'Profile.Telephonenumber'

  2. If you want all the entries of the 'User' table and entries from 'Profile' as a child array try this:

    \UserQuery::create() ->join('User.Profile') ->find() ->toArray();

    //returns an array with all the entries from 'User' table and an child array with entries from 'Profile' table.

Sorry if i made any mistakes, is my first answer on Stackoverflow.
Have a nice day,
M.I.

pacholik
  • 8,607
  • 9
  • 43
  • 55
M. I.
  • 296
  • 1
  • 8
  • Hi @pacholik. Thanks for your feedback. I tried both your suggestions. Suggestion 1 above returns "Profile.Telephonenumber" as the key rather than "Profile" => [ "Telephonenumber" => "xxxxx"] which is what I was anticipating. Suggestion 2 returns all fields of both objects which defeats the purpose of trying to ask for only the fields that I need. – EthanS Jun 18 '16 at 14:44
0

You should probably use withColumn(), e.g.

\UserQuery()::create()
    ->leftJoinWithProfile()
    ->withColumn('Profile.TelephoneNumber', 'TelephoneNumber')
    ->select(['Id', 'Name', 'TelephoneNumber'])
    ->find()
    ->toArray();
Qiniso
  • 2,587
  • 1
  • 24
  • 30