tp框架可以这样使用if ...else...吗?

supplier:供应商
dealer:经销商

select * from table
where
    if(supplier!=0){            //当供应商不为0时,goods_id使用供应商的goods_id 
        goods_id=supplier_goods
    }
    else(dealer!=0){           //当经销商不为0时,goods_id使用经销商的goods_id      
        goods_id=dealer_goods 
    }
    

可以有这种写法吗? tp中又该怎么写?

阅读 4k
7 个回答

//大概这样,只是个大概:
if($supplier !==0 ){ //当供应商不为0时,goods_id使用供应商的goods_id

    $where = 'goods_id=supplier_goods';

}else($dealer !== 0){ //当经销商不为0时,goods_id使用经销商的goods_id

    $where = 'goods_id=dealer_goods'; 

}
$data = $mysql->query("select * from table where {$where}");
建议将判断逻辑放在前面,让SQL一目了然


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

Db::table('table')->where($where)->select();
新手上路,请多包涵

定义一个变量来存储你的两个条件,把这个变量放在where后

1.将条件直接写在where里面;
2.将条件写在变量,然后where里面是该变量;
3.直接用query。

你直接在外面把变量的值判断好,然后查询的时候把变量写进去不是美滋滋吗

用个三目运算就OK了

可怜的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();

只是大概的样子,我没测试过,也不知道到底行不行。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题