开发者

Cakephp 1.3 HABTM issue! :D

Hey, im having this issue with cakephp, bascially i have a Has And Belongs To Many (HABTM) model relationship.

My models are Categroy and Project

bring all project data is fine, it comes out as [0]['Project'], [1]['Project'] ...etc

but when i use the relationship and pull out projects with certain categories in the categories controller i get these tpye of results [0] (all project data in [0] instead of [0]['Project']), [1] (project data and related model info) this is really messing my code up as i use one element view file to render my projects is there any way to return [0]['Project'] for both project controller and categories controller? thanks Chris

Hi sorry if my example isnt clear

i have projects and categories

when i pull a list of projects from the projects controller from my project model the results i get are in this format

[0]['Project'] = array(data...);
[1]['Project'] = array(data...);
[2]['Project'] = array(data...);

this is how the data is pulled and thats fine for me but when i pull projects per cetegory page using the HABTM relationship in the categories controller from the category model this is how my data is returned

['Project'][0] = array(data...);
['Project'][1] = array(data...);
['Project'][2] = array(data...);

which as you can see is a bit of a strain as i want to keep 1 element view file to display my projects, so far my view file prints data like so

<?php print $project['Project']['title']; ?> //data is returned [x]['Project']
<?php print $project['Feature']['title']; ?>

with the way the HABTM relationship is returning data i would need to do this

<?php print $project['title']; ?> //because data is returned ['Project'][x]
<?php print $project['Feature']['title']; ?>

can anyone h开发者_开发技巧elp with this? thanks


This has frustrated me too. I like to have one set of elements that can be used for rendering both "primary" find results as well as related find results.

This is the way I currently deal with the differences in formats of results.

When calling find on, say, a "Project" model and wanting to render the related "Task" list, I run the "Task" key of the results through a function on its way into the element like so:

echo $this->element('tasks/index',array(
    'data'=>make_primary('Task',$data['Task'])
));

My 'make_primary' function is like so:

function make_primary($alias,$data) {
    $d = array();
    foreach($data as $item) {
        $related = array();
        foreach($item as $key => $val) {
            if(!is_numeric($key) && is_array($val)) {
                $related[$key] = $val;
                unset($item[$key]);
            }
        }
        $d[] = array_merge(array($alias=>$item), $related);
    }
    return $d;
}

This returns a new array as though it was the result of a "primary" find query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜