开发者

Cakephp: Model Relations and functions

I have the following Models:

Car hasMany Passengers
Passengers belongTo Car
Passengers hasMany Packages
Package belongTo Passenger

and I find it cumbersome to always have to sum up all packages over all passengers when I want to know how many packages are there in a car.

Is there a way to extend the Car model with a function countPackages() that always returns the amount of packages for the specific car without having to change the 开发者_StackOverflow中文版database?

Also: Is it possible to limit the hasMany relationship to lets say 4 connections (-> that each car can only have 4 passengers)?


Have you tried setting recursive to 2 in a find call? You could create a function in the Car model like so:

public function countPackages($carId = null) {
    $data = $this->find('first', array('recursive' => 2, 'conditions' => array('Car.id' => $carId));
    return count($data['Package']);
}

What this does is return all of the data for a specific car (including the Package information by setting recursive to 2). From there you can then simply return the number of packages that are linked with a vehicle using the count() function.

You can specify the number of associated results that are returned in your hasMany array like so:

public $hasMany = array(
    'Passenger' => array(
        'limit' => 5
    )
);

This example would only return 5 passengers.

Arron Bailiss.
Web & Software Consultant
www.arronbailiss.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜