【发布时间】:2015-09-17 13:32:28
【问题描述】:
我有 3 个 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')
);
Php ActiveRecord 不够聪明,无法像 Rails 的 ActiveRecord 那样处理单数/复数,这就是我给这些奇怪的类名的原因:)
Subcat 和 Content 类实例具有 image 属性(实际上是 image_path)。对于画廊(或滑块,无论它是什么),我需要为Cat 实例选择随机图像。我决定使用来自belongs tothis cat 的子猫的随机图像。或者来自belongs tosubcatbelongs to这只猫的内容。
一个 ruby 等价物看起来就是这样(在 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
我怎样才能重写上面(或更改进的:))的 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="">
【问题讨论】:
标签: php ruby activerecord foreach