Yii2 findOne()超过执行时间

时间:2016-02-29 12:28:38

标签: yii2 yii2-advanced-app

我有一个动作正在执行一个简单的findOne($ id)查询并从数据库返回一行。这超过了最长执行时间。这个方法是由多个类继承的,其中完美正常。我没有覆盖相关模型中的任何find()afterFind()方法。

   public function actionGetone($id)
    {
        $classname = $this->model;
        $model = new $classname;
        return $model::findOne($id);
    }

如果我用以下方法覆盖方法,我没有收到任何错误并按预期工作:

public function actionGetone($id){
        $items = Job::find()->where(['id' => $id])->all();
        return $items;
    }

但是一旦我将其更改为返回return $items[0];,ID就会再次死亡并出现相同的超出错误。

不确定这是否已关联,但我在Maximum execution time of 30 seconds exceeded方法中未提及操作时以及将其添加到访问规则(如下所示)时收到behaviours()错误。但是当我将访问角色更改为['*']时,它会给我Call to a member function checkAccess() on null错误。我没有authManager设置。

public function behaviors()
{
    return [
        'contentNegotiator' => [
            'class' => \yii\filters\ContentNegotiator::className(),
            'formats' => [
                'application/json' => yii\web\Response::FORMAT_JSON,
            ],
        ],
        'authenticator' => [
            'class' => \yii\filters\auth\HttpBearerAuth::className(),
            'only' => [ 'delete','patch','getone'],
        ],
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['delete','patch','getone'],
            'rules' => [
                [
                    'actions' => ['delete','patch','getone'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ]
    ];
}

我很感激任何想法:)

更新

$items = Job::find()->where(['id' => $id]);
return $items;

给出:

{
  "sql": null,
  "on": null,
  "joinWith": null,
  "select": null,
  "selectOption": null,
  "distinct": null,
  "from": null,
  "groupBy": null,
  "join": null,
  "having": null,
  "union": null,
  "params": [],
  "where": {
    "id": "3"
  },
  "limit": null,
  "offset": null,
  "orderBy": null,
  "indexBy": null,
  "modelClass": "common\models\Job",
  "with": null,
  "asArray": null,
  "multiple": null,
  "primaryModel": null,
  "link": null,
  "via": null,
  "inverseOf": null
}

1 个答案:

答案 0 :(得分:0)

发现问题,它与模型的toArray()方法中的递归标志有关。在我的情况下,userjobsjob已在模型users方法中指定了fields()。这导致无限循环。

将此添加到关系模型中以避免无限循环:

public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
    return parent::toArray($fields, $expand, false);
}