[英]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.