duanbu1998 2012-04-11 15:29 采纳率: 0%
浏览 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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?