簡體   English   中英

多列外鍵的yii關系

[英]yii relation for multiple column foreign keys

我有一個表Friend (PersonA, PersonB) 這些是Person(id, name)外鍵。

我想在它們之間建立一個Yii關系。 這是我想出的:

public function relations() {
    return array(
        'friends1' => array(self::HAS_MANY, 'Friend', 'PersonA'),
        'friends2' => array(self::HAS_MANY, 'Friend', 'PersonB'),
    );
}

有沒有辦法將這兩種關系合而為一? 我希望這樣的事情:

public function relations() {
    return array(
        'allFriends' => array(self::HAS_MANY, 'Friend', 'PersonA, PersonB'),
    );
}

有任何想法嗎?

編輯#1:

為了完整friends1 ,讓我們還想像一下,我想像這樣訂購friends1friends2

public function relations() {
    return array(
        'friends1' => array(self::HAS_MANY, 'Friend', 'PersonA', 'order'=>'id ASC'),
        'friends2' => array(self::HAS_MANY, 'Friend', 'PersonB', 'order'=>'id ASC'),
    );
}

這個解決方案為我工作:

覆蓋模型中的__get函數:

public function __get($name)
{
    if(($name == 'friends1') || ($name == 'friends2')) {
        return parent::__get('friends1') + parent::__get('friends2');
    }
    else
        return parent::__get($name);
}

我正在研究的東西完全相同。 我所做的是創建了另一個函數,將兩個關系編譯為一個數組。 這樣做的原因是,即使將兩個關系合並在一起,每次您仍需要測試以查看PersonA或PersonB是當前用戶的ID,還是使用其他ID提取Friends信息。 這是我在模型中創建的函數:

public function getFriends() {
    $all_friends = array();
    foreach($this->friends1 as $friend) {
        if($friend->PersonA == $this->id) {
            $all_friends[] = $friend->PersonA;
        } else {
            $all_friends[] = $friend->PersonB;
        }
    }
    foreach($this->friends2 as $friend) {
        if($friend->PersonA != $this->id) {
            $all_friends[] = $friend->PersonA;
        } else {
            $all_friends[] = $friend->PersonB;
        }
    }
    return $all_friends;
}

另一個選擇:

public function getFriends() {
    $criteria = new CDbCriteria;
    $criteria->compare('PersonA',$this->id);

    $criteria2 = new CDbCriteria;
    $criteria2->compare('PersonB',$this->id);

    $criteria->mergeWith($criteria2,'OR');

    $friends = Challenge::model()->findAll($criteria);
    return $friends;
}

然后,對於任何人,您只能說:

$person = Person::model()->findByPk(1);
$friends = $person->friends;

或者,您可以發回一個CActiveDataProvider來代替數組,該CActiveDataProvider可以進行排序和其他操作。 您可以這樣做:

public function getFriends() {
    $criteria = new CDbCriteria;
    $criteria->compare('PersonA',$this->id);

    $criteria2 = new CDbCriteria;
    $criteria2->compare('PersonB',$this->id);

    $criteria->mergeWith($criteria2,'OR');

    return new CActiveDataProvider('Friend', array(
        'criteria' => $criteria,
    ));
}

然后,由於您具有CActiveDataProvider,因此可以進行排序:

$friends = $user->friends->getData(); //not sorted or anything
//or you can manipulate the CActiveDataprovider
$data = $user->friends;
$data->setSort(array(
    'defaultOrder'=>'PersonA ASC',
));
$friends = $data->getData();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM