mysql - 另一个 "need to pull data from two tables in cakephp"

标签 mysql cakephp cakephp-model

好的,我有两个表,用户和单位。 “单位”属于“用户”,并且“用户”有许多“单位”。我想访问单位表中的所有数据,并附加用户表中的一些数据以供 View 使用。这是我的 Controller 代码:

public function condos() {
    $u=$this->User->Unit->find('all', array('conditions'=>array('type'=>'condo',     'active'=>1)));
    $this->set('allcondos', $u);
}

我有两个模型,用户和单位,这是它们的代码: 来自unit.php:

class Unit extends AppModel {
    var $name='Unit';
    var $belongsTo=array(
        'User'=>array(
        'className'=>'User',
        'foreignKey'=>'user_id'
    ) );
}

以及来自 user.php:

class User extends AppModel {
    var $name='User';
    var $hasMany=array(
        'Unit'=>array(
        'className'=>'Unit',
        'foreignKey'=>'user_id'
    ) );
}

这是我的 View 代码:

<?php foreach ($allcondos as $condo) { ?>

<section class="listings">
<figure>
<img src="<?php echo $condo['Unit']['photo1']; ?>" />
</figure>
<h1><?php echo $condo['Unit']['complex'], ' ', $condo['Unit']['unitnum']; ?></h1>
<h2><?php echo $condo['Unit']['city']; ?>, <?php echo $condo['Unit']['state']; ?> | (<?php echo $condo['User']['area_code']; ?>)<?php echo $condo['User']['exchange'];?>-<?php echo $condo['User']['sln'];?></h2>
<p><?php echo $condo['Unit']['unit_desc']; ?></p>
</section>
<?php } ?>

我在调用 $condo['User']['any_field'] 时遇到问题,因为它返回零“用户”数据。 (它返回“单位”数据就好)。显然,我不知道如何访问这两个表。

如果我在 View 中调试 $allcondos,它看起来像这样:

Array
(
    [0] => Array
    (
        [Unit] => Array
            (
                [id] => 1
                [user_id] => caribeincrentals
                [additional fields] ...
            )

        [User] => Array
            (
                [id] => 
                [user_id] => 
                [additional fields] ...
            )

    )
    [1] => Array ...
)

最佳答案

$this->Unit->find('all', array(
        'conditions' => array(
            'type' => 'condo',
            'active' => 1,
        ),
        'contain' => array(
            'User',
        ),
    ));

使用containable获取相关数据。您也可以使用其中包含的条件来限制您想要的信息。

http://book.cakephp.org/view/1323/Containable

关于mysql - 另一个 "need to pull data from two tables in cakephp",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8481599/

相关文章:

mysql - Go 将非 ascii 形式的值保存为问号

mysql - 如何在 Excel 单元格中保存 blob 文件

php - CakePHP 可包含 : Loading too much relations?

android - 将 Android 应用程序与 CakePhp 网站连接

cakephp 对于 2 个字段来说是唯一的吗?

cakephp - 虚拟字段和模型别名

php - 根据选择字段中的值自动填充表单字段

java - 通过java恢复sql备份后如何通过java删除该备份

php - HABTM join 不会从 cakephp 中的关联数组产生任何结果

php - CakePHP 对象转换为数组?