使用关系查找模型的同级


Find a model's siblings using a relation

这是模型的表:

CREATE TABLE IF NOT EXISTS `SomeModel` (  
  `id` int NOT NULL AUTO_INCREMENT,  
  `parent_id` int NOT NULL
)  

我的目标是能够使用以下方法查询模型及其兄弟姐妹:

SomeModel::model()->with('siblings')->findByPk($id);

这是我目前对这种关系的尝试:

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

问题是我找不到创建条件的方法,以便模型本身不会与 $model->siblings 数组中的同级一起返回。

任何想法都会很棒。

谢谢!

更改与此的关系:

'siblings'=>array(self::HAS_MANY, 'Address', array('parent_id'=>'parent_id'),'condition'=>'siblings.id!=t.id')

编辑:一些解释,在 relation() 的文档中,我们可以为发生的连接指定额外的选项以及这些附加选项:

可以在 rest 数组元素中将其他选项指定为名称-值对。

加上表的默认别名是t因此使用 t.id .

编辑:从评论:

以您想要的方式实现延迟加载将很难完成(我不知道如何,也不确定是否可能),但是我可以建议通过以下方式使当前代码更好

  1. 使用命名范围,在执行预先加载时使用范围,并在范围中添加条件siblings.id!=t.id

    // add this function to your model, and remove the condition from the relation
    public function scopes(){
     return array(
        'eagerSibs'=>array(
            'condition'=>'siblings.id!=t.id',
        ),
     );
    }
    

    使用范围进行预先加载:

    SomeModel::model()->eagerSibs()->with('siblings')->findByPk($id);
    

    这将消除延迟加载$model->siblings的错误

  2. 尽管延迟加载的错误将被删除,但您仍将获得当前记录,但为了
  3. 抵消这一点,您可以添加和使用模型的函数,该函数将在没有当前记录的情况下加载相关记录,但当然您不会使用 $model->siblings ,而是有类似的东西:$model->getLazySibs();

    public function getLazySibs(){
        $sibs=$this->siblings;
        foreach ($sibs as $asib){
            if ($asib->id != $this->id)
                $lazySibs[]=$asib;
        }
        return $lazySibs;
    }