NRaf
NRaf

Reputation: 7549

Converting Propel to JSON with linked entities

I have this setup in a PHP project using Propel (which I'm new to).

User: userid, firstname, lastname

SignIn: signinid, userid, time

SignIn, in this case, is a table containing the times each user signed in.

What I want is to print out a JSON string using Propel of the last ten SignIn entries. On the front end I want to display something like:

Bob Builder signed in at 3:30pm
Max Power signed in at 3:24pm
...

So when I query the last ten entries in SignIn and then call toJSON, I'd like to have the User data for that SignIn record also included in the JSON.

How can I do that?

Note, if there's a better way to do this, I'm open to ideas.

Upvotes: 2

Views: 3716

Answers (2)

Jordan Kasper
Jordan Kasper

Reputation: 13273

Just an alternate solution: you can also override any of the *Base methods in your classes, I've done this many times to add extra info to the toJSON, toArray, or fromArray methods.

In SignIn.php:

public function toJSON() {
  $fields = json_decode(parent::toJSON());
  $user = $this->getUser(); // assumes you have a foreign key set up
  $fields->firstname = $user->getFirstname();
  $fields->lastname = $user->getLastname();
  return json_encode($fields);
}

Now you just query for your SignIn objects and whenever toJSON is called the user data will be appended:

$signIn = SignInQuery::create()
  ->orderByTime('desc')
  ->limit(10)
  ->find()
  ->toJson();

Note that the toJSON override is actually an override of the generic "to[Format]" method in BaseObject which is handled by the code on line 380 (in v1.6): public function __call($name, $params) { ... }

Upvotes: 1

j0k
j0k

Reputation: 22756

One thing about Propel, is that the documentation is really clean, very readable and always helpful.

For your request, you can try the following request. Take a closer look at it, it's readable (as always with Propel)

$signIn = SignInQuery::create()
  ->select(array('User.firstname', 'User.lastname', 'SignIn.time'))
  ->join('User')
  ->orderByTime('desc')
  ->limit(10)
  ->find()
  ->toJson();

Upvotes: 3

Related Questions