【yii2】RESTful接口实现

 需要使用的和创建的文件

controllers/api/ProductController.php

<?php
/**
 * Created by PhpStorm.
 * User: zhudechao
 * Date: 2019/3/24
 * Time: 上午11:03
 */

namespace app\controllers\api;


use app\models\mysql\Product;
use app\models\mysql\Users;
use yii\rest\ActiveController;

class ProductController extends ActiveController
{
    public $modelClass = "app\models\mysql\Product";

    /**
     * 重写请求方式
     * @return array
     */
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        // unset($actions['delete']);
        return $actions;

    }

    public function actionIndex($id)
    {
        return Product::find()
            ->select("product.id,product.user_id,users.name")
            ->leftJoin('users','users.id = product.user_id')
            ->all();
    }

}
models/mysql/Product.php

<?php
/**
 * Created by PhpStorm.
 * User: zhudechao
 * Date: 2019/3/24
 * Time: 上午11:12
 */

namespace app\models\mysql;


use yii\db\ActiveRecord;

class Product extends ActiveRecord
{

}
models/mysql/Users.php

<?php
/**
 * Created by PhpStorm.
 * User: zhudechao
 * Date: 2019/3/24
 * Time: 上午10:31
 */

namespace app\models\mysql;


use yii\db\ActiveRecord;

class Users extends ActiveRecord
{
    //重写过滤字段方法
//    public function fields()
//    {
//        return[
//            'name'
//        ];
//    }
}
config/web.php

<?php

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '_CxqRoQ27hbxPSiy_hycfTnFzV3-yz4w',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
        //这里需要,主要是美化请求方式
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'api/user'],
                ['class' => 'yii\rest\UrlRule', 'controller' => 'api/product'],
                ['class' => 'yii\rest\UrlRule', 'controller' => 'site'],
            ],
        ]
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
}

return $config;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL COMMENT '用户表',
  `num` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `users` VALUES (1, 'ff', 21);
INSERT INTO `users` VALUES (2, '我是用户', 41);


CREATE TABLE `product` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `user_id` int(10) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `product` VALUES (2, 2, '44');
INSERT INTO `product` VALUES (3, 2, 'rr');

猜你喜欢

转载自blog.csdn.net/u010412629/article/details/88778819