Yii2 REST поиск

257
09 февраля 2018, 21:52

Нужно сделать поиск/фильтрацию по любому полю в таблице базы данных через строку запроса типа - http://db5b/web/label-samples?sample_id=7

Модель обычная, созданная Gii - LabelSample.php

<?php
namespace app\models;
use Yii;
/**
 * This is the model class for table "label_sample".
 *
 * @property int $id
 * @property int $sample_id
 * @property int $label_id
 *
 * @property Label $label
 * @property Sample $sample
 */
class LabelSample extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'label_sample';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sample_id', 'label_id'], 'required'],
            [['sample_id', 'label_id'], 'integer'],
            [['sample_id', 'label_id'], 'unique', 'targetAttribute' => ['sample_id', 'label_id']],
            [['label_id'], 'exist', 'skipOnError' => true, 'targetClass' => Label::className(), 'targetAttribute' => ['label_id' => 'id']],
            [['sample_id'], 'exist', 'skipOnError' => true, 'targetClass' => Sample::className(), 'targetAttribute' => ['sample_id' => 'id']],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sample_id' => 'Sample ID',
            'label_id' => 'Label ID',
        ];
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLabel()
    {
        return $this->hasOne(Label::className(), ['id' => 'label_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSample()
    {
        return $this->hasOne(Sample::className(), ['id' => 'sample_id']);
    }
}

В контроллер LabelSampleController.php я добавил function actions() и только.

<?php
namespace app\controllers;
use app\models\LabelSample;
class LabelSampleController extends BaseController
{
    public $modelClass = 'app\models\LabelSample';
    public function actions()
    {
        return [
            'index' => [
                'class' => 'yii\rest\IndexAction',
                'modelClass' => $this->modelClass,
                'prepareDataProvider' => function () {
                    $searchModel = new LabelSample();
                    return $searchModel->search(\Yii::$app->request->queryParams);
                },
            ],
        ];
    }
}

urlManager

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => [
                        'person',
                        'sample',
                        'country',
                        'prefix',
                        'label',
                        'label-sample'
                    ],
                ],
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'sample',
                    'extraPatterns' => [
                        'GET plus-one' => 'plus-one',
                    ],
                ]
            ],
        ],

Но получаю ошибку

"Calling unknown method: app\models\LabelSample::search()",

Попробовал сделать метод search для поиска по параметру sample_id - http://db5b/web/label-samples?sample_id=2

public function search($params)
{
    $query = LabelSample::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
    $this->load($params);
    if (!$this->validate()) {
        print_r($this->errors);
        $query->where('0=1');
        return $dataProvider;
    }
    $query->andFilterWhere([
        'sample_id' => $this->sample_id,
    ]);
    return $dataProvider;
}

но получаю ошибку валидации

Array
(
    [sample_id] => Array
        (
            [0] => Sample ID cannot be blank.
        )
    [label_id] => Array
        (
            [0] => Label ID cannot be blank.
        )
)
[]
READ ALSO
База не видит записи пока не переподключишься

База не видит записи пока не переподключишься

Есть у меня вот такая цепочка событий

281
Подскажите пример проекта на Symfony4

Подскажите пример проекта на Symfony4

После отказа от бандлов каталоги Controller, Entity, Repository and etc находятся в srcЕсли нужно поделить проект на функционалы, то приходится создавать Controller/name,...

241
Не запускается скрипт php cron

Не запускается скрипт php cron

Не срабатывает php скрипт при выставлении задачи в кронеPhp скрипт:

253
Одностраничный сайт

Одностраничный сайт

Всем привет!

342