duanbu1998 2012-04-11 15:29
浏览 45
已采纳

如何基于FK关系在DataMapper PHP构造函数中水合自定义属性

So I have two objects.

class Product extends DataMapper
{
    var $has_many = array('productrating');

    public $averageRating = null;

    function __construct($id = NULL)
    {
        parent::__construct($id);

        echo "my id: " . $this->id;
    }
}

and

class ProductRating extends DataMapper
{
    var $table = "product_ratings";
    var $has_one = array('product');

    function __construct($id = NULL)
    {
        parent::__construct($id);
    }
}

What I would eventually like to accomplish is populate the Product->$averageRating property with, you guessed it, the average rating based on the FK relationship with ProductRatings.

My first thought was to access the relationship, do the math based on the number of ProductRating rows and populate the property inside the constructor. But I'm having issues even accessing the object inside the constructor. This leads me to believe I'm probably going about this the wrong way. How can this be accomplished with DataMapper?

I know the math could be done in the View pages, but I would really like to keep this in the Model if possible.

  • 写回答

1条回答 默认 最新

  • dongyanpai2701 2012-04-12 13:21
    关注

    Ideally I would like this property to be set in the constructor but it was easy enough to add a "getAverageRating" function to the Product class. Accessing the object in this function worked as expected.

    public function getAverageRating()
    {
        $ratings = array();
        foreach($this->productrating as $rating)
        {
            array_push($ratings, $rating->rating);
        }
    
        if(count($ratings) > 0)
        {
            return array_sum($ratings) / $this->productrating->count();
        }
    
        return null;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C