2014-03-24 21 views
0

我是新来的Yii和我有一个表'Student'与像'stdStudentId''stdName'等 我做API领域,所以这个数据应该以JSON返回。现在,因为我想在JSON字段名称只是像'id''name',我不希望所有领域回来后,我做的模型的方法:的Yii:改变当前记录的字段名称

public function APIfindByPk($id){ 
$student = $this->findByPk($id); 
return array(
'id'=>$student->stdStudentId, 
'name'=>$student->stdName, 
'school'=>$student->stdSchool 
); 
} 

的问题是,stdSchool是一个关系在这种情况下,$student->stdSchool返回的数组的字段有schSchoolId,schName等。我不希望字段在JSON中被命名,我也不想从School返回所有字段,我想添加我自己的一些领域。有没有办法在Yii做到这一点,或者我必须通过编写这样的方法来手动执行此操作?

回答

1

我一直在寻找同样的东西。有一个名为Fractal的很好的php库让你实现它:http://fractal.thephpleague.com/

简要地解释一下lib,为你的每个模型创建一个Transformer,它将在你的模型属性和需要的模型属性之间进行映射使用API​​暴露。

class BookTransformer extends Fractal\TransformerAbstract 
{ 
    public function transform(Book $book) 
    { 
     return [ 
      'id' => (int) $book->id, 
      'title' => $book->title, 
      'year' => $book->yr, 
     ]; 
    } 
} 

在你还可以设置关系的变压器,这种模式有:

class BookTransformer extends TransformerAbstract 
{ 
    /** 
    * List of resources relations that can be used 
    * 
    * @var array 
    */ 
    protected $availableEmbeds = [ 
     'author' 
    ]; 

    /** 
    * Turn this item object into a generic array 
    * 
    * @return array 
    */ 
    public function transform(Book $book) 
    { 
     return [ 
      'id' => (int) $book->id, 
      'title' => $book->title, 
      'year' => $book->yr, 
     ]; 
    } 

    /** 
    * Here we are embeding the author of the book 
    * using it's own transformer 
    */ 
    public function embedAuthor(Book $book) 
    { 
     $author = $book->author; 

     return $this->item($author, new AuthorTransformer); 
    } 
} 

所以在最后,你会打电话给

$fractal = new Fractal\Manager(); 
$resource = new Fractal\Resource\Collection($books, new BookTransformer); 
$json = $fractal->createData($resource)->toJson(); 

这并不容易来描述所有的潜在在一个答案中的分形,但你真的应该试试看。 我和Yii一起使用它,所以如果你有一些问题不要犹豫!

0

由于您使用Yii活动记录从数据库中获取值,因此要求数据库使用列别名

普通SQL会像下面这样:

SELECT id AS Student_Number, name AS Student_Name, school AS School_Attending FROM student; 

Yii中,你可以申请标准的findByPK()函数。看到这里供参考:http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findByPk-detail

$criteria = new CDbCriteria(); 
$criteria->select = 'id AS Student_Number'; 
$student = Student::model()->findByPk($id, $criteria); 

注意,为了使用列别名这样,你会在你的学生{}模型来定义虚拟属性Student_Number。

相关问题