I
I
idaho2017-06-15 13:23:49
Yii
idaho, 2017-06-15 13:23:49

YII2 how to select data with specific criteria?

There is one table that stores data about dogs (pedigrees)

CREATE TABLE IF NOT EXISTS `pedigrees` (
  `pedigrees_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `sire` varchar(255) NOT NULL,
  `dam` varchar(255) NOT NULL, 
etc

Output to generated GII CRUD page view.php
You need to select children and partners.
Descendants:
$query.= "FROM pedigrees WHERE sire = $id or dam = $id order by name";

how to translate this into yii2 request?
in the model:
public function getChild(){

        return $this->hasOne(Pedigrees::className(), ['dam' => 'pedigrees_id', 'sire' => 'pedigrees_id']);
    }

view output:
<?php if (isset($model->child)) {
              echo Html::a( Html::encode($model->child->name, $model->child->pedigrees_id), Url::to(['pedigrees/view', 'id' => $model->child->pedigrees_id]));
                }else{  echo "No info";  } ?>

With partners it is a little more difficult:
$query.= "from (SELECT dam as partner_id FROM pedigrees WHERE (sire=$id and dam<>0) group by dam
        union SELECT sire as partner_id FROM pedigrees WHERE (dam=$id and sire<>0) group by sire) t 
        order by (select a.name from pedigrees a where a.pedigrees_id=t.partner_id)";

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
idaho, 2017-06-16
@idaho

in this case, the error Getting unknown property: app\controllers\PedigreesController::partner

public function actionView($id)
    {
       $query = "SELECT dam as partner_id FROM pedigrees WHERE (sire=$id and dam<>0) group by dam union SELECT sire as partner_id FROM pedigrees WHERE (dam=$id and sire<>0) group by sire order by (select a.name from pedigrees a where pedigrees_id=partner_id)";
       $partner = Pedigrees::findBySql($query)->all();
           return $this->render('view', [
            'model' => $this->findModel($id),
            'partner' => $this->partner,
        ]);
    }

conclusion:
<?php foreach ($partners as $name) {
    echo $name->name . '<br>';
}?>

M
Maxim Timofeev, 2017-06-15
@webinar

If I understand you correctly:

public function getDam(){
        return $this->hasMany(Pedigrees::className(), ['dam' => 'pedigrees_id']);
}
public function getSire(){
        return $this->hasMany(Pedigrees::className(), ['sire' => 'pedigrees_id']);
}
public function getSireAndDame(){
        return $this->getSire()->union($this->getDam());
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question