Search code examples
phpjsonyii

How to fetch data from different tables and send it in json format


I am creating functionalities in Yii + extjs-4. I am having two tables as- Poll Option -pollId -optionId -pollQuestion -option -Isactive -pollId -IsPublished

i am creating sendData function,in which i have to retrieve record for given pollId and also options for this pollId from option table and want to send this all record values in json encoede format. So how to send this different tables data together in json format? Please help me....


Solution

  • Use relation at your Poll model (I realized that Poll has many Options). So define:

    public function relations()
    {
        return array(
            'options'=>array(self::HAS_MANY, 'Option', 'poll_id'),
        );
    }
    

    Where poll_id is Option table field.

    Than you need to get array with all data (formatted as you need) like this:

    $data = $pollModel->getAttributes();
    foreach ($pollModel->options as $option) {
        $data = array_merge($data, $option->getAttributes());
    }
    CJSON::encode($data);