Pregunta

I use RedBeanPHP. Suppose I have following structure:

<?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);

Now I want to retrieve all the comment authors without loading them manually (ie. I'd like to avoid code like R::find('comment', 'post_id = ?', [1])). I do it like this:

$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;
}

My problem is that it prints something like this:

post author: john
comment: great comment by

As you can see, there is no information about comment author. What can I do about this except fetching comments/authors manually?

¿Fue útil?

Solución

Finally got it to work: I had to attach 'ownComment.author' => 'user' to R::preload call.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top