2

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.

4

2 回答 2

3

关于 Propel 的一件事是文档非常干净、可读性强并且总是很有帮助。

对于您的请求,您可以尝试以下请求。仔细看一下,它是可读的(与 Propel 一样)

$signIn = SignInQuery::create()
  ->select(array('User.firstname', 'User.lastname', 'SignIn.time'))
  ->join('User')
  ->orderByTime('desc')
  ->limit(10)
  ->find()
  ->toJson();
于 2013-01-18T08:50:57.000 回答
1

只是一个替代解决方案:您还可以覆盖*Base类中的任何方法,我已经多次这样做以向 、 或 方法添加toJSON额外toArray信息fromArray

在 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);
}

现在您只需查询您的 SignIn 对象,并且无论何时toJSON调用,都会附加用户数据:

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

请注意,toJSON覆盖实际上是对 BaseObject 中通用“to[Format]”方法的覆盖,该方法由第 380 行(在 v1.6 中)上的代码处理:public function __call($name, $params) { ... }

于 2013-01-18T15:38:33.143 回答