2015-09-17 44 views
2

我有3個ActiveRecord模型。php activerecord通過一對多關係獲取實例屬性

Cat(類別),Subcat(子類別)和Content。

這些模型之間的關係是

//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') 
    ); 

腓的ActiveRecord不enoough智能處理單數/複數爲Rails的ActiveRecord,這就是爲什麼我把這些奇怪的類名:)

SUBCAT和內容類實例具有圖像屬性(實際上是image_path)。對於圖庫(或滑塊,無論它是什麼),我需要爲Cat實例選擇隨機圖像。我決定使用來自貓的隨機圖像belongs tothis貓。或者從這個貓的belongs tosubcat哪個belongs to的內容。

紅寶石等價物似乎是這樣的(在Cat類中)。

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 

我該如何重寫上述(或更多改進:))的Ruby代碼的PHP等價物?

我實際上試過在Cat類中聲明randomimage()函數。

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)]; 
} 

但是,當我嘗試調用它像視圖文件中,

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

它不會顯示任何東西,當我查看網頁的源代碼有這樣的錯誤:

<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=""> 

回答

0

我編輯了代碼,現在一切都好了。有一個合乎邏輯的問題。 $cats->subcats->contents不是一個有意義的表達。我已經刪除了最後的並且重複了$cats->subcatsas $sc

相關問題