[英]php activerecord getting instance property via one-to-many relationship
我有3個ActiveRecord模型。
目錄(類別),子目錄(子類別)和內容。
這些模型之間的關系是
//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不像Rails的ActiveRecord那樣聰明地處理單數/復數,這就是為什么我給了這些奇怪的類名的原因:)
Subcat和Content類實例具有image屬性(實際上是image_path)。 對於圖庫(或滑塊,無論它是什么),我需要為Cat
實例選擇隨機圖像。 我決定用隨機圖片來自subcats它belongs to
this
貓。 或內容belongs to
subcat
這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="">
我已經編輯了代碼,現在一切正常。 有一個邏輯上的問題。 $cats->subcats->contents
不是有意義的表達。 我剪出最后一個,並將$cats->subcats
迭代as $sc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.