简体   繁体   English

Yii2-如果变量为空,则忽略where子句

[英]Yii2 - Ignore where clause if variable is empty

I have yii2 query with conditional where clause. 我有条件条件where子句的yii2查询。 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 : 我从别人那里读了一些问题,发现是针对mysql table field的:

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

what I want is if the variable is empty, the conditional where() clause is ignore. 我想要的是,如果变量为空,则条件where()子句被忽略。 Is it possible in yii2?? yii2有可能吗?

The filterWhere is the perfect tool to achieve your goals. filterWhere是实现目标的理想工具。

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. 注意:如果值是null,一个空数组,一个空字符串或仅包含空格的字符串,则该值被视为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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