简体   繁体   中英

php activerecord getting instance property via one-to-many relationship

I have 3 ActiveRecord models.

Cat (category), Subcat (subcategory) and Content.

The relationship between these models are

//category
class Cat extends ActiveRecord\Model {
  ...
    static $has_many = array(
    array('subcats')
    );

// subcategory
class Subcat extends ActiveRecord\Model {

  static $has_many = array(
        array('contents')
      );
  static $belongs_to = array(
        array('cat')
      );
//content
class Content extends ActiveRecord\Model {

static $belongs_to = array(
    array('subcat')
    );

Php ActiveRecord is not enoough smart to handle singular/plurals as Rails' ActiveRecord, this is why I gave these weird class names :)

Subcat and Content class instances have image attribute (actually image_path). For a gallery (or slider, whatever it is) I need to select random images for Cat instances. I decided to use random images from subcats which belongs to this cat. Or from contents which belongs to subcat which belongs to this cat.

A ruby equivalent seems like that (inside a Cat class).

def random_image 
    this_cats_images_array = []
    self.subcats.each {|s| this_cats_images_array << s.image_path }
    random_image = this_cats_images_array.sample #or shuffle then sample
    return random_image
end

How can I rewrite the php equivalent of above (or more improved :) ) ruby code?

I actually tried to declare randomimage() function inside Cat class.

public function randomimage() {

$desired_array = array();
foreach ($this->subcats as $sc) { //changed $this->subcats->contents
     array_push($desired_array, $sc->image_path)
}
return $desired_array[array_rand($desired_array)];
}

But when I try to call it inside view file like,

            <img src="assets/uploads/<?php echo $cats_on_sld[$i]->randomimage(); ?>" alt="">

it doesn't show anything and when i view the source of page there is such error:

<img src="assets/uploads/
Notice: Trying to get property of non-object in /var/www/adminpanel/models/Cat.php on line 14

Warning: Invalid argument supplied for foreach() in /var/www/adminpanel/models/Cat.php on line 14

Notice: Undefined index:  in /var/www/adminpanel/models/Cat.php on line 17
" alt="">

I've edited the code and everything is now, ok. There was a logical problem. $cats->subcats->contents was not a meaningful expression. I've cut out the last and iterated over $cats->subcats as $sc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM