物种模型包含
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(
'samples' => array(self::HAS_MANY, 'Sample', 'species_id'),
);
}我想让所有的样本都属于一个物种
$species= Species::model()->with('samples')->findAll(array('condition'=>'tax_id = :no','params'=>array(':no'=>$taxno)));
print_r($species);
$samples=$species->samples; //error here
print_r($samples);当我执行print_r($species)时,它会显示里面的样本值。但它不能传递给$samples=$species->samples;中的$samples,它显示的是error 500。
发布于 2016-09-01 20:03:02
您正在使用findAll获取数据。因此结果将是数组格式。应该使用for loop或foreach来访问这些值。
foreach ($species as $specie) {
echo $specie->samples;
}使用find将只显示一条记录,但findAll会显示多条记录。
发布于 2016-09-01 20:06:16
您可以在Species.php模型中更改您的关系。
Species.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(
'samples' => array(self::BELONGS_TO, 'Sample', 'species_id'),
);
}ControllerName.php文件
$species= Species::model()->with('samples')->findAll(array('condition'=>'tax_id = :no','params'=>array(':no'=>$taxno)));
echo "<pre>";
print_r($species);
//$samples=$species->samples; // You can not used direct object
//print_r($samples); //
foreach ($species as $key => $value) {
echo "<pre>";
echo "Species Object";
print_r($value->attributes);
echo "Samples Object";
print_r($value->samples->attributes);
}
exit;https://stackoverflow.com/questions/39268549
复制相似问题