Yii: change active record field names -


i'm new yii , have table 'student' fields 'stdstudentid', 'stdname', etc. i'm making api, data should returned in json. now, because want field names in json 'id', 'name', , don't want fields returned, made method in model:

public function apifindbypk($id){ $student = $this->findbypk($id); return array( 'id'=>$student->stdstudentid,  'name'=>$student->stdname,  'school'=>$student->stdschool ); } 

the problem is, stdschool relation , in situation, $student->stdschool returns array fields schschoolid, schname, etc. don't want fields named in json, , don't want fields school returned , add fields of own. there way in yii, or i'll have manually writing methods this?

i have been looking same thing. there great php lib named fractal letting achieve it: http://fractal.thephpleague.com/

to explain briefly lib, each of models create transformer doing mapping between model attributes , ones need exposed using api.

class booktransformer extends fractal\transformerabstract {     public function transform(book $book)     {         return [             'id' => (int) $book->id,             'title' => $book->title,             'year' => $book->yr,         ];     } } 

in transformer can set relation model have :

class booktransformer extends transformerabstract {     /**      * list of resources relations can used      *      * @var array      */     protected $availableembeds = [         'author'     ];      /**      * turn item object generic array      *      * @return array      */     public function transform(book $book)     {         return [             'id'    => (int) $book->id,             'title' => $book->title,             'year'  => $book->yr,         ];     }      /**      * here embeding author of book      * using it's own transformer      */     public function embedauthor(book $book)     {         $author = $book->author;          return $this->item($author, new authortransformer);     } } 

so @ end call

$fractal = new fractal\manager(); $resource = new fractal\resource\collection($books, new booktransformer); $json = $fractal->createdata($resource)->tojson(); 

it's not easy describe potential of fractal in 1 answer should give try. i'm using along yii if have question don't hesitate!


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -