鍍金池/ 問答/PHP  數(shù)據(jù)庫/ tp框架可以這樣使用if ...else...嗎?

tp框架可以這樣使用if ...else...嗎?

supplier:供應(yīng)商
dealer:經(jīng)銷商

select * from table
where
    if(supplier!=0){            //當(dāng)供應(yīng)商不為0時(shí),goods_id使用供應(yīng)商的goods_id 
        goods_id=supplier_goods
    }
    else(dealer!=0){           //當(dāng)經(jīng)銷商不為0時(shí),goods_id使用經(jīng)銷商的goods_id      
        goods_id=dealer_goods 
    }
    

可以有這種寫法嗎? tp中又該怎么寫?

回答
編輯回答
拽很帥

//大概這樣,只是個(gè)大概:
if($supplier !==0 ){ //當(dāng)供應(yīng)商不為0時(shí),goods_id使用供應(yīng)商的goods_id

    $where = 'goods_id=supplier_goods';

}else($dealer !== 0){ //當(dāng)經(jīng)銷商不為0時(shí),goods_id使用經(jīng)銷商的goods_id

    $where = 'goods_id=dealer_goods'; 

}
$data = $mysql->query("select * from table where {$where}");
建議將判斷邏輯放在前面,讓SQL一目了然

2018年1月29日 21:07
編輯回答
悶油瓶

1.將條件直接寫在where里面;
2.將條件寫在變量,然后where里面是該變量;
3.直接用query。

2018年9月3日 02:18
編輯回答
囍槑

你直接在外面把變量的值判斷好,然后查詢的時(shí)候把變量寫進(jìn)去不是美滋滋嗎

2017年6月28日 13:28
編輯回答
吢丕

可憐的TP,沒有when
在你的模型類中添加when方法

    public function when($value, $callback, $default = null)
    {
        if ($value) {
            return $callback($this, $value) ?: $this;
        } elseif ($default) {
            return $default($this, $value) ?: $this;
        }

        return $this;
    }

使用方法:

DB::table('users')
    ->when($supplierId, function ($query) use ($supplierId) {
        return $query->where('goods_id', $supplierId);
    }, function ($query) use ($dealerId) {
        return $query->where('goods_id', $dealerId);
    })
    ->select();

只是大概的樣子,我沒測試過,也不知道到底行不行。

2017年4月14日 16:42
編輯回答
離夢

定義一個(gè)變量來存儲你的兩個(gè)條件,把這個(gè)變量放在where后

2018年6月26日 10:40
編輯回答
陌南塵

用個(gè)三目運(yùn)算就OK了

2017年7月26日 04:38
編輯回答
命于你

$where['goods_id'] = ($supplier != 0) ? $supplier_goods : $dealer_goods;

Db::table('table')->where($where)->select();
2017年8月29日 05:51