Skip to content

Instantly share code, notes, and snippets.

@tommymarshall
Last active January 12, 2016 01:49
Show Gist options
  • Save tommymarshall/222fad9aae58df407fbf to your computer and use it in GitHub Desktop.
Save tommymarshall/222fad9aae58df407fbf to your computer and use it in GitHub Desktop.
Attempting to retrieve nested data for a relationship
Note: replies.user is throwing a mysql error. Basically, want to be able to retrieve a Thread with all Replies, then each Reply has a user object
{{ thread.user.fullName }} works fine, but not {{ thread.replies[0].user.fullName
<?php
// Forum_ThreadService.php
if ($record = $this->threadRecord->with(['user', 'category', 'replies', 'replies.user'])->findByPk($id)) {
return Forum_PostModel::populateModel($record);
}
// Forum_ThreadRecord.php
public function defineRelations()
{
return [
'category' => [static::BELONGS_TO, 'Forum_CategoryRecord', 'categoryId'],
'replies' => [static::HAS_MANY, 'Forum_ThreadRecord', 'parentId'],
'user' => [static::HAS_ONE, 'UserRecord', 'id'],
];
}
// Forum_CategoryRecord.php
public function defineRelations()
{
return [
'threads' => [static::HAS_MANY, 'Forum_ThreadRecord', 'categoryId'],
];
}
<?php
namespace Craft;
class ForumVariable
{
public function getThreadById($id)
{
$record = craft()->forum_thread->getThreadById($id);
// This gets me the nested relationship data I am wanting (user.email, user.fullName, etc)
$record->replies = array_map(function($reply)
{
$reply->user = UserRecord::model()->findById($reply->userId);
return $reply;
}, $record->replies);
return $record;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment