restfull api

bug问题 · alijon · 于 2年前 发布 · 860 次阅读

我最近搞一个 朋友圈一样的 一个小程序项目,使用的是restfull Api框架,我对这个框架不熟 原因遇到了很多问题, 发朋友圈 content 表 ,评论comment 表,还有 标签tag表。

主要问题:朋友圈 content 从这个表 读取数据时候 关联读取 评论comment 表中 点赞like,评论内容

controller 怎么让extraFields 执行呢 controller 代码:

<?php


namespace api\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;

class ContentController extends ActiveController
{

    public $modelClass = 'api\models\Content';
    public $enableCsrfValidation = false;

    public function actions()
    {
        $actions = parent::actions();
        // 禁用""index,delete" 和 "create" 操作
        unset($actions['index']);
        return $actions;
    }

    public function actionIndex()
    {
        $model = new $this->modelClass;
        $tagId = Yii::$app->request->get('tagId');
        $page = Yii::$app->request->get('page');
        $condition[] = 'and';
        $condition[] = ['=', 'status', 1];
        if (!empty($tagId) && $tagId != 0) {
            $condition[] = ['=', 'tagId', $tagId];
        }
        $page = isset($page) ? $page : 0;
        $dataProvider = new ActiveDataProvider([
            'query' => $model::find()->where($condition)->orderBy(['id' => SORT_DESC])->asArray(),
            'pagination' => [
                'pageSize' => 10,
                "page" => $page
            ]
        ]);
        return $dataProvider->getModels();
    }
}

moudel

<?php

namespace api\models;

use common\models\ActiveRecord;
use Yii;
use yii\db\QueryInterface;

/**
 * This is the model class for table "content".
 *
 * @property int $id 序号
 * @property string|null $nickName 用户昵称
 * @property string|null $avatarUrl 头像
 * @property string|null $content 内容
 * @property string|null $images 图片
 * @property string|null $location 定位信息
 * @property string|null $failedMsg 备注
 * @property int|null $userId 用户Id
 * @property int|null $tagId 标签Id
 * @property int|null $status 状态
 * @property string|null $openid openId
 * @property int|null $createDate 创建时间
 */
class Content extends ActiveRecord
{
    const STATUS_ACTIVE = 1;
    const STATUS_DELETE = 2;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'content';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['content'], 'string'],
            [['userId', 'createDate', 'status', 'tagId'], 'integer'],
            [['nickName', 'avatarUrl', 'location', 'failedMsg'], 'string', 'max' => 255],
            [['images'], 'string', 'max' => 1024],
            [['openid'], 'string', 'max' => 64],
        ];
    }


    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '序号',
            'nickName' => '用户昵称',
            'avatarUrl' => '头像',
            'content' => '内容',
            'images' => '图片',
            'location' => '定位信息',
            'failedMsg' => '备注',
            'status' => '状态',
            'userId' => '用户Id',
            'tagId' => '标签',
            'openid' => 'openId',
            'createDate' => '创建时间',
        ];
    }

    /**
     * @return array
     */
    public static function getStatus()
    {
        return [
            '' => '默认',
            self::STATUS_ACTIVE => '正常',
            self::STATUS_DEFAULT => '待审核',
            self::STATUS_DELETE => '删除',
        ];
    }
    // public function fields()
    // {
    //     return [
    //         'id',
    //         'createDate' => function () {
    //             return Yii::$app->formatter->asDatetime($this->createDate, 'php:Y-m-d H:i:s');
    //         },
    //     ];
    // }
    public function extraFields()
    {
        return [
            'reply',
            'like',
        ];
    }


    public function getContent()
    {
        return $this->hasMany(Content::class, ['tagId' => 'id']);
    }

    public function getReply()
    {
        return $this->hasMany(Reply::class, ['parentId' => 'id'])->onCondition([Reply::tableName() . '.likes' => 0, '.status' => 1]);
    }

    public function getLike()
    {
        return $this->hasMany(Reply::class, ['parentId' => 'id'])->onCondition([Reply::tableName() . '.likes' => 1, '.status' => 1]);
    }

    public function search()
    {
        $tagId = $this->tagId;
        return parent::find()
            ->andFilterWhere(['tagId' => $tagId])
            ->andFilterWhere(['status' => 1]);
    }

    public function defaultValue()
    {
        return [
            'createDate' => time(),
            'tagId' => 0,
            'status' => 0,
        ];
    }


    public function beforeSave($insert)
    {
        $time = time();
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->createDate = $time;
                return true;
            }
            return true;
        }
        return false;
    }
}

共收到 1 条回复 问题提问
Fecmall#12年前 0 个赞

这些东西都是没有定法的,AR这个方式适合比较简单的一些快速查询

如果您的查询,适合join查询处理,那么你可以在query部分加上join的一些代码,也是可以完成的

但是,如果你的需求需要查询出来单独处理,那么你就可以抛弃这种用法

给你一个fecmall使用yii2 框架,开发api的例子

https://github.com/fecshop/yii2_fecshop/blob/master/app/appapi/modules/V1/controllers/CategoryController.php#L25

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics