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

时间:2017-09-27 02:30:40

标签: php mysql yii2

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

$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表字段:

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

我想要的是如果变量为空,则条件where()子句为ignore。是否有可能在yii2 ??

1 个答案:

答案 0 :(得分:2)

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

例如,

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

注意:如果值为null,空数组,空字符串或仅包含空格的字符串,则该值被视为空。

相关问题