0
/**
 * This is the model class for table "hashtag".
 *
 * @property string $text
 *
 * @property TweetHashtag[] $tweetHashtags
 * @property Tweet[] $tweets
 */
class Hashtag extends ActiveRecord
{
.........
    public function getTweetHashtags()
    {
        return $this->hasMany(TweetHashtag::className(), ['hashtag_text' => 'text']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTweets()
    {
        return $this->hasMany(Tweet::className(), ['id' => 'tweet_id'])->viaTable('tweet_hashtag', ['hashtag_text' => 'text']);
    }
}

When I do in some component

   $hashtags = Hashtag::find()
                ->with('tweets')
                ->where(['text' => $hashtagText])
                ->all();

            foreach($hashtags as $hashtag)
            {
                print_r($hashtag->tweets);
            }

It`s working but why tweets - field accessed only via magic method and how can i fix it? And tweetHashtags working well.

Class Tweet have same relationship but public function getHashtags() working without this problem.

1
  • Do you have an error if you access to tweets-field not using magic method? Are all tweets fields accessible only from magic method? Mar 11, 2016 at 22:30

1 Answer 1

1

Your question is not clear. Each method on a Component class that start with get (like getName) can be accessed with property form (e.g. name). On special case, relations of Yii's ActiveRecord, if you access to relation by property form, you get results. In fact $this->tweets is a shorthand for $this->getTweets()->all().

P.S: On Yii2 Document http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#accessing-relational-data:

Note: While this concept looks similar to the object property feature, there is an important difference. For normal object properties the property value is of the same type as the defining getter method. A relation method however returns an yii\db\ActiveQuery instance, while accessing a relation property will either return a yii\db\ActiveRecord instance or an array of these.

$customer->orders; // is an array of `Order` objects
$customer->getOrders(); // returns an ActiveQuery instance

This is useful for creating customized queries, which is described in the next section.

1
  • this link should also be useful about how setters & getters are working in Yii. Mar 19, 2016 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.