具有关系结果的Yii2 ActiveRecord转换为JSON

时间:2018-04-24 09:18:25

标签: php mysql activerecord yii2 foreign-keys

我有一个名为textAreas的数据库表,其中Yii2 ActiveRecord模型带有主键id列(以及其他一些列,但它们并不重要)。

我还有一个名为text的表,带有Yii2 ActiveRecord模型,称为TextCtrl,主键为id,外键textControllerId与textAreas的id相关联,一个名为lang的列和一个名为content的列。一个textArea有很多文本(基本上是不同语言的文本)。

现在用户可以选择一种语言。然后,我想从表格中选择所有textAreas,并根据用户的lang选择为他们提供正确的内容。

通常这是通过SQL连接完成的,但我认为ActiveRecord也应提供此功能。

我的代码到目前为止: textAreas.php:

//TextAreas.php ActiveRecord model for table textAreas

class TextAreas extends ActiveRecord
{
    /**
     * @property int $id
     * @property int $width
     * @property int $height
     */

    /**
     * @ignore
     */
    public static function tableName()
    {
        return "{{textAreas}}";
    }

    /**
     * Get all textAreas and their dimensions if user is authorized and website in development mode
     */
    public static function getAllTextAreas()
    {
        // check if user is authorized and website is in development mode
        if(! Yii::$app->user->can('updateContent') || YII_ENV != 'dev')
        {
            $textArea = 'notAuthorized';
            return [$textArea];
        }

        // get all textareas and their properties
        $textArea = self::find()
            ->joinWith('text')
            ->all();

        return $textArea;
    }

    /**
     * fill textareas with content
     * @param int $lang language setting, if null language from session is used
     */
    public function getText($lang = null)
    {
        //get language from session
        if(!$lang)
        {
            $lang = LangCtrl::getStoredLanguage();
        }

        //return the content
        return $this->hasOne(TextCtrl::className(), ['textControllerId' => 'id'])
                ->where(['lang' => $lang]);
    }
}

textCtrl.php文本表的ActiveRecord模型:

//TextCtrl ActiveRecord model for text table

class TextCtrl extends ActiveRecord
{
    /**
     * @property int $id
     * @property int $textControllerId id of text block on web page
     * @property int $lang language of text
     * @property string $content the text itself
     */

    /**
     * @ignore
     */
    public static function tableName()
    {
        return "{{text}}";  
    }

    //Other methods which don't matter
}

现在,在控制器操作中,我这样做:

$textAreas = TextAreas::getAllTextAreas();

$response = Yii::$app->response;
$response->format = Response::FORMAT_JSON;  

return $textAreas;

结果如下:

[{"id":1,"width":100,"height":16},{"id":2,"width":100,"height":16}, more database entries...]

但我其实想要像

这样的东西
[{"id":1,"width":100,"height":16,"content":"MyContent1"},{"id":2,"width":100,"height":16,"content":"MyContent2"}, more database entries...]

content字段填充了text表中的内容。

有人能提供一些帮助吗?

2 个答案:

答案 0 :(得分:1)

当然,您可以根据您的关系在fields()方法中添加新字段:

public function fields()
{
    return array_merge(
        parent::fields(),
        [
            'content' => function () {
                if (!$this->text) {
                    return '';
                }

                return $this->text->content;
            },
        ]
    );
}

答案 1 :(得分:0)

看看Converting Objects to Arrays

vue create <project-name>