0

Нужно сделать поиск/фильтрацию по любому полю в таблице базы данных через строку запроса типа - 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.
        )

)
[]
7
  • Всё правильно, у вас же нет метода search в LabelSample. 8 фев 2018 в 13:47
  • @ZhukovRoman и что мне нужно в методе этом указать? Как есть составить?
    – n.osennij
    8 фев 2018 в 13:55
  • вам нужно создать отдельно модель поиска например LabelSampleSearch
    – Blacknife
    8 фев 2018 в 16:38
  • @Blacknife а можно пример какой-нибудь?
    – n.osennij
    8 фев 2018 в 21:07
  • @n.osennij yiiframework.com/wiki/653/… 9 фев 2018 в 9:21

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.