ActiveRecord's relation doesn't resolve when being used without :: operator

Hi, please see this Code:




<?php

$posts = Post::model()->findAll();

foreach($posts as $post) echo $post->author;

?>



works fine, but :




<?php

$post = new Post();

$posts = $post->findAll();

foreach($posts as $post) echo $post->author;

?>



says post.author is not defined.

Unfortunately even this won’t work:




<?php

$post = new Post();

$posts = $post->with('author')->findAll();

foreach($posts as $post) echo $post->author;

?>



I need to have this function because a $dynamic_var::model()->findAll() only works in PHP >5.3 (AFAIK!),

and the $obj = new $dynamic_var; $objects = $dynamic_var->findAll() isn’t able to handle relations.

Or am I doing something wrong/is there another way to accomplish this?

Thanks in advance

I did some investigation…

Scenario: grandparent 1:n to parent 1:n to child




<?php


$var_i_want_to_fetch = "parent.grandparent";


$childobj = new Child();

$childobjs = $childobj->findAll();


echo $childobjs[0]->$var_i_want_to_fetch;


?>



This doesn’t work because he translates this into

child->parent.grandparent

but he could be more intelligent and translate this into

child->parent->grandparent

maybe we can make the magic _get() function of ActiveRecord a little bit more intelligent and allow for parent.grandparent syntax?

My Investigations went further… :)

i would suggest something like this:

CActiveRecord.php:




 /**

   * PHP getter magic method.

   * This method is overridden so that AR attributes can be accessed like properties.

   * @param string property name

   * @return mixed property value

   * @see getAttribute

   */

  public function __get($name)

  {   

    if(isset($this->_attributes[$name]))

      return $this->_attributes[$name];

    else if(isset($this->getMetaData()->columns[$name]))

      return null;

    else if(isset($this->_related[$name]))

      return $this->_related[$name];

    else if(isset($this->getMetaData()->relations[$name]))

      return $this->getRelated($name);

    else if(strstr($name, '.') != FALSE) {

      $data = explode('.', $name);

      return($this->getRelated($data[0])->$data[1]);

    }

    else

      return parent::__get($name);

  }



qiang: what do you think about this small but useful addition?




$objects = CActiveRecord::model($dynamic_var)->findAll();