2016-09-01 37 views
0

物種模型包含警予的CActiveRecord的findAll與錯誤500

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$samples=$species->samples;它顯示error 500

+0

與此錯誤什麼信息? – aslawin

+0

您可以發佈您的表格結構。 –

回答

0

您正在使用findAll來獲取數據。所以結果將以數組格式。您應該使用for循環或foreach來訪問這些值。

foreach ($species as $specie) { 
    echo $specie->samples; 
} 

使用找到會給只有一個記錄,但的findAll給多個記錄。

0

你可以改變你在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;