cakePHP 3 Query ifnull

前端 未结 1 1793
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 08:41

I wonder what would be the best way to prevent null results in a ResultSet. I\'m on cake 3.5.13 and I\'m using cases, like:

private function addCase($isforeign,         


        
相关标签:
1条回答
  • 2021-01-23 09:29

    The functions builder can create any function you want, you just need to call it, and the magic method call handler of the builder will create a generic function call in case there is no concrete method implemented, ie func()->ifnull() will just work.

    However, IFNULL is MySQL/SQLite specific, so in order to keep things as portable as possible, I'd suggest to simply use an ELSE case instead, one that selects 0 instead of NULL in case the conditions evaluate to FALSE.

    $query
        ->newExpr()
        ->addCase(
            [
                $query->newExpr()->add([
                    'Sales.isforeign' => $isforeign,
                    'Sales.source' => $source
                ])
            ],
            [1, 0],
            ['integer', 'integer']
        );
    

    That should generate SQL similar to:

    CASE WHEN (Sales.isforeign = 0 AND Sales.source = 1) THEN 1 ELSE 0 END
    

    See also

    • Cookbook > Database Access & ORM > Query Builder > Using SQL Functions
    • Cookbook > Database Access & ORM > Query Builder > Using SQL Functions > Case Statements
    0 讨论(0)
提交回复
热议问题