Skip to content

Instantly share code, notes, and snippets.

@acodesmith
Last active February 9, 2018 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acodesmith/fdb7b4c7c3642d8533e34ca7ab8290e7 to your computer and use it in GitHub Desktop.
Save acodesmith/fdb7b4c7c3642d8533e34ca7ab8290e7 to your computer and use it in GitHub Desktop.
Example of advanced relationships in Yii2
<?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']);
}
<?php
$programs = Products::find()->courses()->asArray()->all();
<?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