Yii Relations错误尝试获取非对象的属性

Abu*_*yah 3 php mysql yii

我有Cinema table和City table,我通过id与这个表有关系.当我回显结果时,我有PHP注意"试图获取非对象的属性"

问题是什么 ?还是我错过了什么?

我的代码: 电影模型

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(
        'countryCode' => array(self::BELONGS_TO, 'TblCountry', 'country_code'),
        'city' => array(self::BELONGS_TO, 'TblCity', 'city_id'),
        'tblCinemaMovies' => array(self::HAS_MANY, 'TblCinemaMovies', 'cinema_id'),
        'tblDays' => array(self::HAS_MANY, 'TblDay', 'cinema_id'),
        'tblShowtimes' => array(self::HAS_MANY, 'TblShowtime', 'cinema_id'),
    );
}
Run Code Online (Sandbox Code Playgroud)

城市模型

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(
        'tblCinemas' => array(self::HAS_MANY, 'TblCinema', 'city_id'),
        'countryCode' => array(self::BELONGS_TO, 'TblCountry', 'country_code'),
    );
}
Run Code Online (Sandbox Code Playgroud)

查看文件:

<?php echo $model->city_id->name; ?>
Run Code Online (Sandbox Code Playgroud)

Vla*_*d V 5

我建议你总是检查关系是否没有返回null或者是empty array.

以下代码适用于HAS_ONEBELONGS_TO关系类型:

$cinema = Cinema::model()->find(); // get a cinema instance, assuming there is at least one row in the database.
$city = $cinema->city; // get the relation 
if ($city !== null) {
    // $city is a valid model
} else {
    // $city is null, the corresponding row does not exist in the database
}
Run Code Online (Sandbox Code Playgroud)

您也可以在不使用新变量的情况下进行此检查(在本例中$city):

if ($cinema->city!==null) {
    // the relation is available
}
Run Code Online (Sandbox Code Playgroud)

检查关系是否未返回null是避免PHP错误"尝试获取非对象属性"的最佳方法.此外,如果您遇到类似的错误,建议使用类似var_dump()或更好的调试器等功能.

另外,请注意从relations()函数返回的数组中的数组键是必须访问以获取关系模型的属性:

public function relations() {
    return array(
         'city' => array( ... ),
         // city is the property that has to be accessed
         // Yii's conventions recommend to use 'city_id' for the foreign key column name
    );
}
Run Code Online (Sandbox Code Playgroud)

另请注意,遵循Yii的约定关系和列的约定是很好的,以避免对属性和关系使用相同的名称 - 在这种情况下,关系将不可用,并且可能是"尝试访问属性播放关系时会弹出"非对象".

最后一件事,当使用HAS_MANYMANY_TO_MANY关系时,即使只有一个模型可用,关系也会返回一个模型数组,如果没有可用模型,则返回一个空数组.

文档中的说明:http: //www.yiiframework.com/doc/guide/1.1/en/database.arr#performing-relational-query