简体   繁体   中英

Yii2 - Ignore where clause if variable is empty

I have yii2 query with conditional where clause. this is my query :

$query = new Query();

$query->select
    (['pengeluaran.id'])
    ->from('surat_jalan, pengeluaran')
    ->where('surat_jalan.no_bus=:no_bus',['no_bus'=>$no_bus])

    //this is my conditional query
    ->andWhere(['between', 'pengeluaran.tgl_pengeluaran', $awal, $akhir])
    ->andWhere('pengeluaran.nama_toko=:nama_toko',['nama_toko'=>$nama_toko])
    ->andWhere('pengeluaran.metode_pembayaran=:metode_pembayaran',['metode_pembayaran'=>$metode_pembayaran])
    ->andWhere('pengeluaran.waktu_pembayaran=:waktu_pembayaran',['waktu_pembayaran'=>$waktu_pembayaran])
    //this is my conditional query

    ->andWhere('surat_jalan.id_surat_jalan=pengeluaran.id_surat_jalan');

$command = $query->createCommand();
$data_id_pengeluaran = $command->queryAll();

I read some question from others and what I found is for mysql table field :

->andWhere(['not', ['activated_at' => null]]);

what I want is if the variable is empty, the conditional where() clause is ignore. Is it possible in yii2??

The filterWhere is the perfect tool to achieve your goals.

For example,

// This will not appear in the finally statement if $val is empty.
$query->andFilterWhere(['activated_at' => $val])

Note: A value is considered empty if it is null, an empty array, an empty string or a string consisting of whitespaces only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM