· 7 years ago · Sep 13, 2018, 03:58 AM
1Find a model's siblings using a relation
2CREATE TABLE IF NOT EXISTS `SomeModel` (
3 `id` int NOT NULL AUTO_INCREMENT,
4 `parent_id` int NOT NULL
5)
6
7SomeModel::model()->with('siblings')->findByPk($id);
8
9public function relations()
10{
11 return array(
12 'siblings' => array(self::HAS_MANY, 'SomeModel', array('parent_id'=>'parent_id')),
13 );
14}
15
16'siblings'=>array(self::HAS_MANY, 'Address', array('parent_id'=>'parent_id'),'condition'=>'siblings.id!=t.id')
17
18// add this function to your model, and remove the condition from the relation
19public function scopes(){
20 return array(
21 'eagerSibs'=>array(
22 'condition'=>'siblings.id!=t.id',
23 ),
24 );
25}
26
27SomeModel::model()->eagerSibs()->with('siblings')->findByPk($id);
28
29public function getLazySibs(){
30 $sibs=$this->siblings;
31 foreach ($sibs as $asib){
32 if ($asib->id != $this->id)
33 $lazySibs[]=$asib;
34 }
35 return $lazySibs;
36}