开发者

Find() one of each matching field CakePHP

开发者 https://www.devze.com 2023-01-27 21:55 出处:网络
Trips hasMany Legs Airports has no associations How can I find the cheapest trip for each destination airport using CakePHP?

Trips hasMany Legs

Airports has no associations

How can I find the cheapest trip for each destination airport using CakePHP?

Right now, the only thing I can think of to do is to foreach through an array of airports. This would require hundreds of queries to the database (which I think is not the fastest way of doing it).

function getCheapestTrip($origin){

$airports=$this->Airport->getAirports();
foreach($airports as $airport):
$cheapest_flights=$this->Trip->find('first', 
array(
'conditions'=>array('Leg.origin'=>$origin, 'MIN(Trip.price) as price'),
'fields'=>array('Trip.origin','price','Leg.destination','Leg.depart','Leg.arrive'),
'recursive'=>2,
));
 endforeach;
}
}  

Also, I think that this data type stuff should be in the model per CakePHP conventions (Fat models, skinny controllers). I read that to call a different model's function such as getAirports I can use loadModel but I found that in CakePHP's controller method section. How should one get an开发者_开发问答other model's data/model function into anothers?

Thanks!


The answer to your second question, "How to load a model within another model?" can be found here.


If you're looking for a better algorithm rigth now I do not have the solution.

Mine is a design solution: basically you should add a field to your destination airport which will be updated every time you add a new flight so you have your information directly in your destination record.

This stands if I have understood your problem. I'm not english so I'm not familiar with the semantic of "leg" associated to a trip (to me it's a body part)


The problem you're solving is the Traveling Salesman Problem: http://en.wikipedia.org/wiki/Travelling_salesman_problem

From what I've read on how google maps does it, you'll want to precompute your most common routes and connections. Keep that precomputed info in a cheap cache (memcache prolly). Basically, you won't be able to recalculate each time, so calc a few common ones and build a precomputed cache.

WRT the algorithm, some google searching will be your friend for tips and tricks. This problem has been solved many times (none are exactly computationally efficient, which is why you should precompute and cache).

0

精彩评论

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