D
D
DarkByte20152018-09-17 09:33:12
Yii
DarkByte2015, 2018-09-17 09:33:12

Where relation?

I have a model like this:

/**
 * @property int $id
 * @property int $article_id
 * @property int $amount
 * @property int $created_at
 * @property int $updated_at
 *
 * @property-read Article $article
 * @property-read PaymentFile[] $files
 * @property-read bool $isCompleted
 */
class ArticlePayment extends ActiveRecord {
  public static function tableName() {
        return '{{%article_payment}}';
    }
  
    public function getArticle() {
        return $this->hasOne(Article::class, ['id' => 'article_id']);
    }

    public function getFiles() {
        return $this->hasMany(PaymentFile::class, ['payment_id' => 'id'])->where(['is_deleted' => false]);
    }

    public function getIsCompleted() {
        return $this->getFiles()->select('count(id) > 0')->groupBy('id')->having('count(id) > 0')->asArray();
    }
}

I want to add the isCompleted property, but I don't know how to do it correctly... Now the isCompleted property returns an array of arrays with one element like ['count(id) > 0' => '1'], instead of bool as I need. Besides it is necessary to me that I could use this property in where requests. For example:
$article->getPayments()->where(['isCompleted' => true]);

But the ORM does not convert this property to a subquery in this case. It just tries to find a column with that name, but it doesn't exist.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DarkByte2015, 2018-09-17
@DarkByte2015

Found a solution

public function getFilesAggregation() {
  return $this->getFiles()
    ->alias('f')
    ->select(['isCompleted' => 'count(f.id) > 0'])
    ->groupBy('f.id')
    ->having('count(f.id) > 0')
    ->asArray();
}

public function getIsCompleted() {
  return $this->isNewRecord ? false : (bool)$this->filesAggregation[0]['isCompleted'];
}

You can even use it in a subquery:
$article->getPayments()->joinWith('filesAggregation');

A
Arman, 2018-09-17
@Arik

1. Maybe try count instead of select? or just a select with a limit of 1? then if there is at least one record then true
2.
Fine-tuning the Query classes create the isCompleted() method and add the necessary conditions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question