TP5模型使用笔记

模型里的命名规范

<?php 
 namespace app\index\model;
 use think\Model;
 class User extends Model 
 {
    #命名 imooc_user -> User.php User
    #     imooc_user_info -> UserInfo.php UserInfo
 }

对模型的操作

<?php 

    $db = Db::name('user');
    #+++++++++++++++++++++++++++++ 数据库连接
    use think\Controller;
    use think\Db;
    use think\config;

class Index extends Controller{
    public function index(){
        Db::connect();

        Db::connect([
            // 数据库参数
        ]);

        Db::connect("mysql://root:root@127.0.0.1:3306/dbname#utf8");

        Db::connect('db_config01');     
        [config.php]:
        'db_config01' =>[
            //数据库参数
        ]

    }
} 
    #+++++++++++++++++++++++++++++ 数据库查询
    Db::query("select * from dbtable where id =?",[1]);

    Db::execute("insert into dbtable set username=?,password=?,email=?",['username','password','email']);

    Db::table('dbtable')->where(['id'=>1]) ->select();//查询所有

    Db::table('dbtable')->find();//查询一条

    Db::table('dbtable') ->value('username');

    Db::table('dbtable')->column('username','email');

    Db::name('user')->select();

    db('user')->select();

    //不用频繁调用数据库
    db('user',[],false)->find();

    #+++++++++++++++++++++++++++++数据库添加
    $db = Db::table('dbtable');

    $db->insert([
        'email' =>'',
        'username' => '',
        'password' => '',
    ]);

    //获取插入的ID
    $db->insertGetId([
        'email' =>'',
        'username' => '',
        'password' => '',
    ]);
    //插入多条
    $data = [];
    for ($i=0; $i < 10; $i++) { 
        # code...
        $data[] = [
            'email' =>'email{$i}',
            'username' => 'username{$i}',
            'password' => 'password{$i}',
        ];
    }
    $db ->insertAll($data);



    #+++++++++++++++++++++++++++++ 数据更新 

    $db = Db::table('dbtable');

    $db->where(['id'=> 1])->updata([
        'username'->'',
    ]);


    // 只更新一个字段
    $db->where(['id'=>1])->setField('username','用户名');

    //该字段如num每次增加n
    $db->where(['id'=>1])->setInc('num',n);
    //该字段如num每次减少n
    $db->where(['id'=>1])->setDec('num',n);

    #+++++++++++++++++++++++++++++数据库删除

    $db = Db::table('dbtable');

    $db->where(['id'=> 1])->delete();

    $db->delete(主键的值);

    #+++++++++++++++++++++++++++++条件构造器

    $db = Db::table('dbtable');

    //返回sql语句
    $db->where(['id'=> 1])->buildSql();    
    #EQ  = 
    #NEQ <>
    #LT  <
    #ELT <=
    #GT  >
    #EGT >=
    #BETWEEN BETWEEN * ADN * 
    #NOTBETWEEN NOTBETWEEN * AND *
    #IN IN (*,*)
    #NOTIN NOT IN (*,*)

    where("id=1")
    where("id",1)
    where("id","<>",1)
    where("id","EQ",1)
    where("id","between","1,10")
    where("id","between",[1,10])
    where(['id'=>1])
    where(['id'=>['IN',[1,2,3,4,5]]])
    where("id","EXP","not in (1,2,3)")

    $db->where(['id'=> 1])->where()->buildSql();
    $db->where(['id'=> 1])->whereOr("id","between",[1,10])->buildSql();

    #+++++++++++++++++++++++++++++ 链式操作
    $db = Db::table('dbtable');

    $db->where()->find();
    $db->where()->field()->find();
    $db->where()->field()->order('id desc')->find();
    $db->where()->field()->order('id desc')->limit(3,5)->find();
    //分页
    $db->where()->field()->order('id desc')->page(3,5)->find();
    //分组查询 order失效的
    $db->where()->field()->order('id desc')->group("`group`")->find();




    #+++++++++++++++++++++++++++++ 模型操作

    use app\index\model\User;
    class Index extends Controller 
    {
        public function index()
        {
            #code
        }
    }


    $res = User::get(1);   //取得id为1的数据
    $res->toArray();

    $res = new User;
    $res = $user::get(1);
    $res->toArray();

#--------------分割线---------------#


    use think\Loader;
    class Index extends Controller 
    {
        public function index()
        {
            #code
        }
    }


    $user = Loader::model("User");
    $res = $user::get(1);
    $res->toArray();

#--------------分割线---------------#
#助手函数
    $user = model("User");
    $res = $user::get(1);
    $res->toArray();

#+++++++++++++++++++++++++++++ 模型查询 

    use app\index\model\User;
    class Index extends Controller 
    {
        public function index()
        {
            #code
        }
    }

//取得username的值
    $res = User::get(1);   
    $res->username;
//所有值
    $res->toArray();


#--------------分割线---------------#
    $res = User::get(function($query){
        $query ->where('id','eq',1);
               ->field()
    });

#--------------分割线---------------#

    $res = User::where("id",10)->field()->find();


#--------------分割线---------------#
    $res = User::all("1,2,3");
    foreach ($variable as $key ){
        # code...
        $val -> toArray();
    }

    $res = User::all(function($query){
        $query ->where('id','eq',1);
               ->field()
    });
    foreach ($variable as $key ){
        # code...
        $val -> toArray();
    }
#--------------分割线---------------#
    User::where()->value('email');

    User::column("返回值","下标");


#+++++++++++++++++++++++++++++ 模型添加数据  
#[index.php]

    User::create([
        'username'=>'',
    ]);
#--------------分割线---------------#
#传递数据库不存在的字段
#$_POST
    User::create([
        'username'=>'',
        'demo'=>''
    ],true);  //变为true即可


$userModel = new User;
$userModel->allowField(true)->save([
        'username'=>'',
        'psw'=>'',
        'email'=>''
]);


#--------------分割线---------------#
#传递允许插入的字段名
#$_POST
    User::create([
        'username'=>'',
        'psw'=>'',
        'email'=>''
    ],['username','psw']);  

$userModel = new User;
$userModel->allowField(['email'])->save([
        'username'=>'',
        'psw'=>'',
        'email'=>''
]);





$userModel = new User;
$userModel -> username = '用户名';
$userModel -> email = '邮件地址';
$userModel ->save();

$userModel = new User;
$userModel->save([
        'username'=>'',
        'psw'=>'',
        'email'=>''
]);


$userModel = new User;
$userModel->saveAll([
        ['username'=>'1'],
        ['username'=>'2'],
        ['username'=>'3'],
]);


#+++++++++++++++++++++++++++++ 模型更新数据  
    sUser::update([
        'username' => ''
    ],['id'=>2]);


    User::update([
        'username' => ''
    ],function($query){
        $query;
    });


    User::where()->update();

    $userModel = User::get(1);
    $userModel->username = '123';
    $userModel->save();

    $userModel = new User;
    $userModel->save([
        ['username'=>'1'],      
    ],['id'=>1]);

    $userModel->save([
        'email' => ''
    ],function($query){
        $query;
    });

    $userModel->saveAll([
        ['id'=>1,'username'=>1],
        ['id'=>2,'username'=>2],
    ]);

#+++++++++++++++++++++++++++++ 模型删除数据  

    User::destroy(['id'=>2]);
    User::destroy(function($query){
        $query;
    });

    $userModel = User::get(1);
    $userModel->delete();

    User::where()->delete();


#+++++++++++++++++++++++++++++ 模型聚合操作 
    User::count();  

    User::where()->count();

    User::where()->max('num');

    User::where()->min('num');

    User::where()->sum('num');

    User::where()->avg('num');//平均值


#+++++++++++++++++++++++++++++ 模型获取器  

    sex :0 1 2

[model.php]

    public function getSexAttr($val){
        switch ($val) {
            case 0:
                return "未知";
                break;
            case 1:
                return "男";
                break;
            case 2:
                return "女";
                break;
            default:
                # code...
                break;
        }
    }
[index.php]

    User::get(3)->sex;


#+++++++++++++++++++++++++++++ 模型修改器 
[index.php]

    User::create([
        'username'=>'',
        'psw'   =>'',
    ]);

[model.php]
    public function setPasswordAttr($val){
        return md5($val);
    }

    public function setPasswordAttr($val,$data){
        return $val.$data['email'];
    }

#+++++++++++++++++++++++++++++ 自动完成 
[model.php]
    protected $auto = [
        'time'
    ];
    protected $insert = [
        'time_insert'
    ];
    protected $updata = [
        'time_update'
    ];
    public function setTimeAttr(){
        return time();
    }
    public function setTimeInsertAttr(){
        return time();
    }
    public function setTimeUpdateAttr(){
        return time();
    }

#+++++++++++++++++++++++++++++ 时间戳
[database.php]

    'auto_timestamp'    =>  true,

[index.php]

    User::create([

    ]);  

#-------------------------
[model.php]

    protected $autoWriteTimestamp = true;

    //设置时间戳的字段名
    protected $createtime = 'create_at';
    protected $updatetime = 'update_at';

#+++++++++++++++++++++++++++++ 软删除 
[数据库字段]
    delete_time =>  null

[model]

    use think\Model;
    use traits\model\SoftDelete;

    class User extends Model
{
    use SoftDelete;
}
[index]

    #获取被软删除的数据
    User::withTrashed(true)->find(1);

    User::OnlyTrashed(true)->select();
#------------------------------------------------------------
    [model]

    protected $deleteTime = 'delete_at';


阅读更多
版权声明:转载请注明出处~ https://blog.csdn.net/seven_north/article/details/79956341
文章标签: TP5笔记
个人分类: TP5笔记
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭