Last active
February 9, 2018 16:04
-
-
Save acodesmith/fdb7b4c7c3642d8533e34ca7ab8290e7 to your computer and use it in GitHub Desktop.
Example of advanced relationships in Yii2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @return \yii\db\ActiveQuery | |
*/ | |
public function getProduct_variants() | |
{ | |
return $this->hasMany(ProductVariants::className(), ['product_id' => 'id'])->andWhere(['<>','product_variants.status', Statuses::STATUS_REMOVED]); | |
} | |
/** | |
* Dynamic relationship based on relationship_type | |
* @return null | |
*/ | |
public function getProgram() | |
{ | |
return $this->hasOne(Programs::className(), ['id' => 'relationship_id']); | |
} | |
/** | |
* @return $this | |
*/ | |
public function getCourse() | |
{ | |
return $this->hasOne(Courses::className(),['id' => 'course_id']) | |
->viaTable(Programs::tableName(), ['id' => 'relationship_id']); | |
} | |
/** | |
* @return $this | |
*/ | |
public function getLocation() | |
{ | |
return $this->hasOne(Locations::className(),['id' => 'location_id']) | |
->viaTable(Programs::tableName(), ['id' => 'relationship_id']); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$programs = Products::find()->courses()->asArray()->all(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Products table | |
/** | |
* @return $this | |
*/ | |
public function courses() { | |
return $this->abc() | |
->with(['product_variants']) | |
->joinWith(['product_type']) | |
->andWhere(['product_types.slug' => Products::SCENARIO_COURSE]) | |
->joinWith(['program'=> function($q) { | |
$q->from('programs p'); | |
}]) | |
->joinWith(['location'=> function($q) { | |
$q->from('locations l'); | |
}]) | |
->joinWith(['course' => function($q) { | |
$q->from('courses c'); | |
}]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment