L
L
Lorem Ipsum2019-11-18 13:11:48
Yii
Lorem Ipsum, 2019-11-18 13:11:48

Yii2 how to use findBySql in Rest controller?

Hello! I can't figure out how to do findBySql in Rest controller? Not much experience with Rest, please help)
Need to return slightly modified data from the database based on the request

"SELECT *, ST_AsGeoJSON(geom) AS geo_json FROM projects"

Rest Controller:
<?php namespace frontend\controllers;

use yii\rest\ActiveController;
use app\models\Project;
use yii\data\ActiveDataProvider;

class ProjectController extends ActiveController
{
    public $modelClass = Project::class;

    public function behaviors() {
        return array_merge(parent::behaviors(), [
            'corsFilter'  => [
                'class' => \yii\filters\Cors::class,
                'cors'  => [
                    'Origin'                           => ['http://localhost:3000'],
                    'Access-Control-Request-Method'    => ['POST', 'GET'],
                    'Access-Control-Allow-Credentials' => true,
                    'Access-Control-Max-Age'           => 3600,
                ],
            ],

        ]);
    }

    public function actions()
    {
        $actions = parent::actions();

        unset($actions['create'], $actions['update'], $actions['delete']);

        $actions['index'] = [
            'class'               => 'yii\rest\IndexAction',
            'modelClass'          => $this->modelClass,
            'prepareDataProvider' => function () {
                $model        = new $this->modelClass;
                $query        = $model::find();
                $dataProvider = new ActiveDataProvider([
                    'query'      => $query,
                    'pagination' => false,
                ]);

                return $dataProvider;
            },
        ];

        return $actions;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
coderisimo, 2019-11-18
@GeorgeGeorge

What does the controller method look like, what does the error look like, is there a model?
If you need to modify the fields a bit, you can use public function fields()
https://www.yiiframework.com/doc/guide/2.0/ru/rest...

public function fields()
{
    return [
        // название поля совпадает с именем атрибута
        'id',
        // название поля "email", атрибут "email_address"
        'email' => 'email_address',
        // вот здесь модифицируйте на здоровье!
        'name' => function () {
            return $this->first_name . ' ' . $this->last_name;
        },
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question