yii\rest\Action::findModel PHP Method

findModel() public method

If the data model is not found, a 404 HTTP exception will be raised.
public findModel ( string $id ) : yii\db\ActiveRecordInterface
$id string the ID of the model to be loaded. If the model has a composite primary key, the ID must be a string of the primary key values separated by commas. The order of the primary key values should follow that returned by the `primaryKey()` method of the model.
return yii\db\ActiveRecordInterface the model found
    public function findModel($id)
    {
        if ($this->findModel !== null) {
            return call_user_func($this->findModel, $id, $this);
        }
        /* @var $modelClass ActiveRecordInterface */
        $modelClass = $this->modelClass;
        $keys = $modelClass::primaryKey();
        if (count($keys) > 1) {
            $values = explode(',', $id);
            if (count($keys) === count($values)) {
                $model = $modelClass::findOne(array_combine($keys, $values));
            }
        } elseif ($id !== null) {
            $model = $modelClass::findOne($id);
        }
        if (isset($model)) {
            return $model;
        } else {
            throw new NotFoundHttpException("Object not found: {$id}");
        }
    }

Usage Example

Beispiel #1
0
 public function findModel($id = null)
 {
     if (is_null($id)) {
         $modelClass = $this->modelClass;
         $emptyPrimaryKey = array_flip($modelClass::primaryKey());
         $primaryKey = array_merge($emptyPrimaryKey, array_intersect_key(Yii::$app->getRequest()->getQueryParams(), $emptyPrimaryKey));
         $id = implode(',', array_values($primaryKey));
     }
     return parent::findModel($id);
 }
All Usage Examples Of yii\rest\Action::findModel