Last active
January 12, 2016 01:49
-
-
Save tommymarshall/222fad9aae58df407fbf to your computer and use it in GitHub Desktop.
Attempting to retrieve nested data for a relationship
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'], | |
]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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