关于php:Yii2-如果变量为空,则忽略where子句

Yii2 - Ignore where clause if variable is empty

我有带有条件where子句的yii2查询。这是我的查询:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$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();

我从别人那里读了一些问题,发现是针对mysql表字段的:

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

我想要的是,如果变量为空,则条件where()子句将被忽略。 yii2有可能吗?


filterWhere是实现目标的完美工具。

例如,

1
2
// 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.