2012-10-12 65 views
0

GoodsCats模型與未來的關係:的Yii:動態變化模型關係類型與模型() - >與()

public function relations(){ 
    return array(
    'GoodsCatsContent' => array(self::HAS_MANY, 'GoodsCatsContent', 'parent_id'), 
); 
} 

,現在我想找到所有GoodsCats要素,但有一個孩子元素(具體language_id):

$cats = GoodsCats::model()->with(
    array(
    'GoodsCatsContent'=>array(
     'on'=>'languages_id = 1' 
    ) 
) 
)->findAll(); 

並且其中每個elemt是recive陣列等GoodsCats.id=>GoodsCatsContent.name

CHtml::listData(cats, 'id', 'name') 

但是現在我得到一個錯誤GoodsCats.name not defined。 當我設置GoodsCats關係爲self::HAS_ONE所有的作品都很好,但我無法改變整個項目。 它有可能以某種方式設置model()->with()使用未定義的關係類型,但一個特定的?

UPD我的模型規則:

GoodsCatsContent

public function rules() 
{ 
    return array(
     array('parent_id', 'required'), 
     array('active', 'numerical', 'integerOnly'=>true), 
     array('parent_id', 'length', 'max'=>10), 
     array('name, seo_title, seo_keywords, seo_description', 'length', 'max'=>255), 
     array('short_content, content', 'safe'), 
     array('id, parent_id, active, name, short_content, content, seo_title, seo_keywords, seo_description', 'safe', 'on'=>'search'), 
    ); 
} 

GoodsCats

public function rules() 
{ 
    return array(
     array('active, prior', 'numerical', 'integerOnly'=>true), 
     array('photo', 'length', 'max'=>255), 
     array('id, photo, active, prior', 'safe', 'on'=>'search'), 
    ); 
} 
+0

你的模型是什麼樣的? – Jon

+0

@Jon你是不是指每個模型的'rules()'或'search()'? –

+0

我的意思是'rules()'。 – Jon

回答

0

您不能動態更改關係類型。

但是,既然你確信使用​​只給你一個相關GoodsCatsContent記錄,你可以做到這一點,而不是使用listData()

$myList=array(); 
foreach ($cats as $acat){ 
    $myList[$acat->id]=isset($acat->GoodsCatsContent[0]->name)? $acat->GoodsCatsContent[0]->name :''; 
    // you need isset incase some of the GoodsCats don't have a related GoodsCatsContent 
} 
// you can now use $myList as you would have used the array returned by listData() 

因爲這是一個HAS_MANY關係,每個GoodsCats將有x個的相關GoodsCatsContent記錄,因此即使只有1條相關記錄,該關係也會始終返回一個array,如果沒有相關記錄,該關係將返回一個空數組。因此,當有1條相關記錄時,relationName[0]將返回該記錄。

0

嘗試

$cats = GoodsCats::model()->with(
    array(
    'GoodsCatsContent'=>array(
     'condition'=>'languages_id = 1' 
    ) 
) 
)->findAll(); 

$cats = GoodsCats::model()->with('GoodsCatsContent')->findAll('languages_id = 1'); 
+0

沒有運氣。 'CHtml :: listData($ cats,'id','GoodsCatsContent.name')'返回帶有'GoodsCats' id的數組,但帶有空的'GoodsCatsContent'名稱:'Array([2] => [3] => [4 ] => ...)' –