【问题标题】:Yii: cannot get the relationsYii:无法获取关系
【发布时间】:2015-12-01 06:49:32
【问题描述】:

我的模特:

零售项目:

public function relations()
{
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
                    'retailItemDetail' => array(self::BELONGS_TO, 'Item', array('item_id' => 'id')),
        );
}

我的看法:

$criteria = new CDbCriteria();
//$criteria->condition= "item_id = $id";
$items = RetailItem::model()->findAll($criteria);

CVarDumper::dump($items[0],3,true);

结果:

......
[relations] => array()
......

为什么关系array() 是空的?

【问题讨论】:

    标签: php yii conditional-statements


    【解决方案1】:

    这里的例子:

    //sql
    CREATE TABLE transaction (
        id INT(11) NOT NULL AUTO_INCREMENT,
        userId INT(11) NULL DEFAULT NULL,
        PRIMARY KEY (id)
    )
    COLLATE=utf8_general_ci
    ENGINE=InnoDB;
    
    CREATE TABLE user (
        id INT(11) NOT NULL AUTO_INCREMENT,
        PRIMARY KEY (id)
    )
    COLLATE=utf8_general_ci
    ENGINE=InnoDB;
    
    INSERT INTO user (id) VALUES (1);
    INSERT INTO user (id) VALUES (2);
    INSERT INTO transaction (id, userId) VALUES (2, 1);
    INSERT INTO transaction (userId) VALUES (1);
    
    //models
    class User2 extends CActiveRecord
    {
        public function tableName()
        {
            return 'user';
        }
        //... etc
    } 
    
    class Transaction2 extends CActiveRecord
    {
        public function tableName()
        {
            return 'transaction';
        }
    
    
        public function relations()
        {
            return array(
                'user' => array(self::BELONGS_TO, 'User2', 'userId'),
            );
        }
        //... etc
    }
    

    使用方法:

    $test = Transaction2::model()->findAll();
    echo '<pre>';
    print_r($test[0]->user);
    echo '</pre>';
    die();
    

    【讨论】:

    • 抱歉,我想获取一些数据,例如 $items[0]->retailItemDetail->description 。但我不能。我不知道它有什么问题,因为我尝试将关系复制到另一个模型,并正确运行。
    • item_idRetailItemDetail 中的列,idItem 中的列对吗?
    • 是的,item_id 是 RetailItem 模型中的列。我在另一个模型中使用了相同的方法,它的工作。但我不能使用与 RetailItem 模型相同的关系函数。
    • 我可以得到模型中除了关系之外的所有数据。这让我很沮丧。
    • 检查我的答案。如果 RetailItem 模型 中的 item_id 列,它必须工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多