我使用RedBeanPHP。假设我有以下结构:
<?php
require_once 'redbean/RedBean/redbean.inc.php';
R::setup('sqlite:test.sqlite');
$user = R::dispense('user', 1);
$user->name = 'john';
R::store($user);
$post = R::dispense('post', 1);
$post->author = $user;
$post->text = 'great post';
R::store($post);
$comment = R::dispense('comment', 1);
$comment->post = $post;
$comment->author = $user;
$comment->text = 'great comment';
R::store($comment);
现在我想要检索所有评论作者而不用手动加载它们(即我想避免像R::find('comment', 'post_id = ?', [1])
这样的代码)。我是这样做的:
$post = R::load('post', 1);
R::preload($post,
[
'author' => 'user', //this makes $post->author->name work
'comment',
//what I've tried in order to get $post->comments[...]->author->name to work:
//'comment.author',
//'comment.author' => 'comment.user',
//'comment.author' => 'user',
//'author' => 'comment.user',
]);
echo 'post author: ' . $post->author->name
. PHP_EOL;
foreach ($post->ownComment as $comment)
{
echo 'comment: ' . $comment->text
. ' by ' . $comment->author->name
. PHP_EOL;
}
我的问题是它打印的内容如下:
post author: john
comment: great comment by
如您所见,没有关于评论作者的信息。除了手动提取评论/作者外,我该怎么办?
答案 0 :(得分:0)
最后让它发挥作用:我必须将'ownComment.author' => 'user'
附加到R::preload
来电。