I am working on REST API under Yii2, however I have an issue with what the model should return per different actions.
For example in listing actions I need to for example to return 4 attributes and for the details action I need to return 10 attributes from the same model.
What is the best or standard way in Yii2 to implement this.
Example:
/articles
return [id, title, image, date]
/articles/7
return [id, title, image, date, author, likes, last_review]
Thank you
Just write methods in your model.
class MyModel extends ActiveRecord
{
private static $fieldset_1 = [
'id', 'title', 'image', 'date'
];
private static $fieldset_2 = [
'id', 'title', 'image', 'date', 'author', 'likes', 'last_review'
];
public static function get(int $id)
{
if($id > 0) {
return static::find()
->select(self::$fieldset_1)
->where(['id' => $id])
->asArray()
->one();
}
}
public static function getList()
{
return static::find()
->select(self::$fieldset_2)
->asArray()
->all();
}
}
In Controller
class MyController extends Controller{
public function actionListing(){
return $this->asJson(MyModel::getList());
}
public function actionDetails($id){
return $this->asJson(MyModel::get((int)$id));
}
}
for /article/7 :
public function actionView($id)
{
return User::findOne($id);
}
or
public function actionView($id)
{
return User::find()->select([id, title, image, date, author, likes,last_review])->one();
}
for /articles :
public function actionIndex()
{
return User::find()->select([id, title, image, date])->all();
}