简体   繁体   English

CakePHP从遥远的关系中获取数据

[英]CakePHP Get data from a distant relationship

The following is an example and not used in my app but I hope to get the theory and apply it to my own application after getting the answerer. 以下是一个示例,未在我的应用程序中使用,但我希望获得理论并将其应用于答题人之后将其应用于我自己的应用程序。

So take a simple app with 3 tables: Users, Locations, and Posts 因此,以一个包含3个表的简单应用为例:用户,位置和帖子

and the relationships are a Post has a User and a User has a Location but a Location doesn't necessarily have a User. 并且关系是一个帖子有一个用户,一个用户有一个位置,但是一个位置不一定有一个用户。

If I pull a list of Posts and then show the User of that Post this is fine. 如果我拉出一个帖子列表,然后显示该帖子的用户,那就很好。 But what If I wanted to pull the Location of the User? 但是,如果我想提取用户的位置怎么办? As their is no relation between the Post and the Location but their is one between the User and the Post. 因为它们不是帖子和位置之间的关系,而是它们是用户和帖子之间的关系。 How would I do it? 我该怎么办?

Example of the loop: 循环示例:

<?php foreach($posts as $post): ?>

<?php echo $this->Html->link($post['User']['firstname'], array('controller'=>'users','action'=>'view','userName'=>$post['User']['username'])); ?> in <?php echo $this->Html->link($post['Place']['name'], array('controller'=>'places','action'=>'view',$post['Place']['id'])); ?>

and this is the controller: 这是控制器:

function index()
    {
        $posts = $this->paginate();

        if (isset($this->params['requested']))
        {
            return $posts;
        }
        else
        {
            $this->set('posts', $posts);
        }
    }

Now this would not work as Place is undefined! 现在这将无法正常工作,因为Place是未定义的! How do I do it? 我该怎么做?

I have heard Containable mentioned but some examples would be great! 我听说有可Containable但有些例子会很棒!

Have a look at the containable behaviour. 看一下可遏制的行为。 Not only will it allow you to solve this problem but it will also help your application performance by ensuring only required data is retrieved, parsed and returned. 它不仅使您能够解决此问题,而且还可以通过确保仅检索,解析和返回所需的数据来帮助提高应用程序性能。

eg 例如

function index()
    {
        $this->paginate = array(
           'contain' => array('User' => array('Location')),
        );
        $posts = $this->paginate();

        if (isset($this->params['requested']))
        {
            return $posts;
        }
        else
        {
            $this->set('posts', $posts);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM