【问题标题】:php activerecord getting instance property via one-to-many relationshipphp activerecord通过一对多关系获取实例属性
【发布时间】: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


    【解决方案1】:

    我已经编辑了代码,现在一切正常。有一个逻辑问题。 $cats-&gt;subcats-&gt;contents 不是一个有意义的表达。我已经剪掉了最后一个并迭代了$cats-&gt;subcatsas $sc

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2020-07-27
      • 2020-12-30
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多