Georgi Stefkoff
Georgi Stefkoff

Reputation: 97

Yii2 findOne returns me an array, but not an Object(ActiveRecord)

I'm trying to use afterFind method of an Model

public function afterFind() {                


        $group = GroupMember::findOne(1);;

        Yii::info($group->id);

        parent::afterFind();
    }

And the error is

Trying to get property of non-object

I found that findOne return an array with column values.

My question is what I'm doing wrong, or just afterFind if making this?

Thanks.

Upvotes: 1

Views: 5913

Answers (3)

Roberto Braga
Roberto Braga

Reputation: 559

This question is quite old but arogachev is right. findOne either return an ActiveRecord or Null, you got null About the documentation, you read the method description and not what it return, just go to end and you find:

return static|null
ActiveRecord instance matching the condition, or null if nothing matches.

The description: Returns a single active record model instance by a primary key or an array of column values. The phrase is not very clear but it means that you can pass as query filter an id or an array of columns name => value to use as query filter. Since version 2.0.37 Expression can be passed

Upvotes: 0

Georgi Stefkoff
Georgi Stefkoff

Reputation: 97

@Awesome AP - this is not urgent syntax error(with the ";;")

@arogachev - in the documentation there is said that

Returns a single active record model instance by a primary key or an array of column values

and its really returns me an array, but I don't know why.

Luckily I fix it by $group = GroupMember::find(1)->one();.

But tanks you all for helping me.

Upvotes: 1

arogachev
arogachev

Reputation: 33538

Look at the docs, findOne() can not return array.

Most likely record with id = 1 dosn't exist and you get null. afterFind() has nothing to do with it.

Upvotes: 2

Related Questions