yii2 API将多个记录输入到一个表

时间:2018-06-21 12:19:31

标签: php yii2

我将制作用于在一个表中创建多个记录的API。 这是我在Controller

中的操作
class RecorditemController extends Controller
{    
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => HttpBearerAuth::className(),
        ];

        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ];

        return $behaviors;
    }

    public function actionCreate()
    {        
        $count = count(Yii::$app->request->post('Recorditem', []));       
        $products = [new Recorditem()];        
        for($i = 1; $i < $count; $i++) 
        {
            $products[] = new Recorditem();
        }        
        if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {
            foreach ($products as $product) 
            {        
                $product->save(false);
            }
            return ['status' => 'true'];
        }
    }      

    public function verbs()
    {
        return [
            'create' => ['post'],
        ];
    }   
}

为了进行测试,我以这种方式发送JSON:

[
    {
        "food_id": 13,
        "quantity": 5,
        "order_id": 1
    },
    {
        "food_id": 13,
        "quantity": 6,
        "order_id": 1
    }
]

但是我的方法行不通。它什么也不返回。我的错误在哪里或还有其他解决方法?

0 个答案:

没有答案