TP5 多條件whereOr查詢


問題背景:最近在用ThinkPHP 5開發項目的過程中,發現根據篩選條件做or查詢的時候,連貫操作不可以使用where進行條件查詢了。

首先列出一個user數據表的信息:

uid

uname

grade(年級)

class(班級)

sex(性別)

1

1號

1

2

1

2

2號

1

1

2

3

3號

3

3

2

4

4號

4

2

1

5

5號

2

5

1

6

6號

1

6

2

7

7號

1

1

1

8

8號

2

3

1

9

9號

2

2

1

10

10號

3

1

2

 

數據表展現了10位同學的年級、班級、性別信息

現在要查詢數據為

grade=1 or class= or sex=2

TP3中想要or查詢

條件可以為:

$condition['grade'] = 1;

$condition['class'] = 3;

$condition['sex'] = 2;

$condtion['_logic'] = 'OR';

$list = M(‘user’)->where($condtion)->findall();

然后在TP5中嘗試用where去這么查詢發現一直在報錯,查了手冊之后發現TP5取消了_logic作為查詢方式,而是新增了whereOr方法,下面是TP5中查詢方式

User.php

<?php
namespace app\index\controller;

use app\index\model\UserModel;

class User
{
    public function index()
    {
        $condition['grade'] = 1;
        $condition['class'] = 3;
        $condition['sex'] = 2;
        $UserModel = new UserModel;
        $list = $UserModel->getlistwhereOr($condition);
        
        print_r($list);
    }
}        

UserModel.php

<?php
namespace app\index\model;
use app\common\model\CommonModel;
use think\Db;
use think\Model;

class UserModel extends CommonModel
{
    public function __construct(){
        parent::__construct();
         
    } 
    
    protected $name = 'User';
    
    public function getlistwhereOr($condition) {
        $list =Db::name($this->name)->whereOr($condition)->select();
        return $list;
    }
}

執行User.php 發現打印出來的數據就是我們要的篩選數據,

總結:TP5相比TP3中更新了很多我們經常用到的查詢方式,而且寫法更人性化,需要經常的去整理查看這些新方法

by as


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM