鍍金池/ 問答/PHP  數(shù)據(jù)庫/ 如果使用thinkphp查詢數(shù)據(jù)庫忽略不存在的查詢條件?

如果使用thinkphp查詢數(shù)據(jù)庫忽略不存在的查詢條件?

$condition 里面會(huì)有時(shí)間的條件,這個(gè)時(shí)間的條件是可選條件,現(xiàn)在就想如果時(shí)間條件不存在如何把時(shí)間條件給去除?而時(shí)間條件存在時(shí),則加上時(shí)間條件查詢結(jié)果?

方法一:數(shù)組不存在會(huì)報(bào)錯(cuò)。

public static function getHomeworkByStudentId($id, $conditions)
{
    $conditions['startTime'] = '2018-09-01';
    $conditions['endTime']   = '2018-09-02';

    $result = self::where('id', '=', $id)
        ->whereTime('recordTime', '>', $conditions['startTime'])
        ->whereTime('recordTime', '<', $conditions['endTime'])
        ->select();

    return $result;
}

方法二:如果時(shí)間條件不存在,生成sql的時(shí)間條件就會(huì)變成0就像下面這樣:

SELECT * FROM `homework` WHERE `id` = '1' AND ( `recordTime` >= 0 AND `recordTime` <= 0 )
public static function getHomeworkByStudentId($id, $conditions)
{
    $conditions['startTime'] = '2018-09-01';
    $conditions['endTime']   = '2018-09-02';

    $result =  self::where('id', ':id')
        ->whereTime('recordTime', '>=', ':startTime')
        ->whereTime('recordTime', '<=', ':endTime')
        ->bind($conditions)
        ->select();

    return $result;
}
回答
編輯回答
放開她

ThinkPHP 5.1文檔,最后一個(gè) 條件查詢。

https://www.kancloud.cn/manua...
2018年8月21日 12:24