douhanzhuo6905 2019-01-31 12:07 采纳率: 100%
浏览 298

Yii 2 Fields在Active Record Models中起作用

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

  • 写回答

2条回答 默认 最新

  • duaedf6509 2019-01-31 16:41
    关注

    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));
        }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用