【问题标题】:Yii2 ActiveRecord with relation result convert to JSONYii2 ActiveRecord 与关系结果转换为 JSON
【发布时间】:2018-10-04 11:44:59
【问题描述】:

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

我还有一个名为 text 的表,它使用 Yii2 ActiveRecord 模型,称为 TextCtrl,主键 id,外键 textControllerId 链接到来自 textAreas 的 id,列名为 lang和一个名为content 的列。一个textArea有很多文本(基本上是不同语言的相同文本)。

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

通常这是通过 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 表中的内容填充。

有人可以提供帮助吗?

【问题讨论】:

    标签: php mysql activerecord yii2 foreign-keys


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      看看Converting Objects to Arrays

      $textAreas = TextAreas::getAllTextAreas();
      
      $response = Yii::$app->response;
      $response->format = Response::FORMAT_JSON; 
      
      return ArrayHelper::toArray($textAreas, [
          TextAreas::class => [
              'id',
              'width',
              'height',
              'content' => function ($data) {
                  return $data->text->text;
              },
          ],
      ]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-24
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        • 2013-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多