yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.23k stars 6.92k forks source link

How to get relationship data for REST? #3319

Closed jungyuyu closed 10 years ago

jungyuyu commented 10 years ago

I need GET the user post list, request url as follow: http://domain/restapi/users/1/posts

I add getPosts() in /models/User.php public function getPosts() { return $this->hasMany(Post::className(), ['author_ID' => 'ID']); }

But does not work, need modify urlManager? or extend some method()? how to do it? guide me, please!

My tables as follow: CREATE TABLE yii2_user ( ID bigint(20) unsigned NOT NULL AUTO_INCREMENT, ... )

CREATE TABLE yii2_post ( ID bigint(20) unsigned NOT NULL AUTO_INCREMENT, author_ID bigint(20) unsigned NOT NULL DEFAULT '0', ... )

Best regards,

Ragazzo commented 10 years ago

you can use expand parameter, see this info in rest guide. However getting particular one info about related model is not supported now, so this issue can be open i think for further discussion @qiangxue ?

jungyuyu commented 10 years ago

Thanks Ragazzo,

I modified /models/User.php to add extraFields() etc as follow:

public function extraFields() { return ['posts']; }

and request GET http://domain/restapi/users/1?expand=posts

It's work fine, but not enough to support multilevel data for REST, e.g. Just GET one http://domain/restapi/users/1/posts/123

Because i use AngularJS to design client, and AngularJS have full REST feature: https://github.com/mgonto/restangular

If Yii2 can full support, it's really great!

Ragazzo commented 10 years ago

@jungyuyu well, it will have support once somone from core or other developers will have time for that ) you also can submit PR if ;) Lets keep this issue open for this feature discussion.

cebe commented 10 years ago

duplicate of #3303