Home php教程 php手册 ThinkPHP的CURD方法及查询方法一览

ThinkPHP的CURD方法及查询方法一览

Jun 13, 2016 am 10:52 AM
thinkphp at a glance Basic operations operate database method Inquire of

所谓CURD。即对数据库操作的四个基本操作(CURD):C:create(创建)、U:update(更新)、R:read(读取)和D:detele(删除)。
在ThinkPHP中,并不是一定以这几个名字的方法,这里列出常见的:select,find,findAll,save,create等方法:

D读取:
select->()查询数据集,和findAll->()相同。例如:
$User->where(‘status=1′)->order(‘create_time’)->limit(10)->select();
注意:在连贯操作中除了select方法必须放到最后一个外,其他的连贯操作的方法调用顺序没有先后,例如,下面的代码和上面的等效:
$User->order(‘create_time’)->where(‘status=1′)->limit(10)->select();

如果丌习惯使用连贯操作癿话,新版迓支持直接使用参数迕行查诟癿方式。例如上面癿代码可以改
写为:
$User->select(array('order'=>'create_time', 'where'=>'status=1', 'limit'=>'10'));


find->()方法,和以上两种方法类似。区别在只返回一条数据。可以和getField->()获取一条记录的某个字段值一起用。


select和findall效果一样,返回的是一个二维数组。如
array(1) {
      [0] => array(8)
{ ["rank_id"] => string(3) “151″
["rank_name"] => string(7) “测试9″
["rank_memo"] => string(3) “123″
["uid"] => string(5) “59471″
["rank_kw"] => string(6) “重要”
["rank_uptime"] => string(10) “1280202914″
["isverify"] => string(1) “0″
["ishot"] => string(1) “0″
}
   }
find的效果如下,返回的是一个一维数组:
array(8) {
["rank_id"] => string(3) “151″
["rank_name"] => string(7) “测试9″
["rank_memo"] => string(3) “123″
["uid"] => string(5) “59471″
["rank_kw"] => string(6) “重要”
["rank_uptime"] => string(10) “
1280202914″ ["isverify"] => string(1) “0″
["ishot"] => string(1) “0″
}

Where方法:用于查询或者更新条件的定义

Table方法:定义要操作的数据表名称
$Model->Table(‘think_user user’)->where(‘status>1′)->select();

field方法:定义要查询的字段
field方法的参数支持字符串和数组,例如,
$Model->field(‘id,nickname as name’)->select();
$Model->field(array(‘id’,'nickname’=>’name’))->select();
如果不使用field方法指定字段的话,默认和使用field(‘*’)等效。

 

U更新,C创建:

data,add,save方法:数据对象赋值,添加,保存。例如:
$data['name'] = ‘ThinkPHP’;
$data['email'] = ‘ThinkPHP@gmail.com’;
$Model->data($data)->add();//新增,相当于insert,连贯写法
$Model->add($data); //新增,相当于insert,非连贯写法
$Model->data($data)->where(‘id=3′)->save(); //修改,相当于update

需要注意的是,save方法的话,如果数据没有变化,那么默认返回的操作是FALSE。但是这个save执行是OK的,这个需要注意。

create->()自动从POST的字段组成形如$data的数据

$User=D("User");
$User->create(); //默认通过表单提交的数据进行创建
$User->add(); //新增

如果你癿主键是自劢增长类型,幵丏如果揑入数据成功癿话,Add方法癿迒回值就是最新揑入癿主键值,可以直接获叏。 

使用data方法创建癿数据对象丌会迕行自劢验证和过滤操作,请自行处理。但在迕行add戒者
save操作癿旪候,数据表中丌存在癿字段以及非法癿数据类型(例如对象、数组等非标量数据)是会自
劢过滤癿,丌用担心非数据表字段癿写入导致 SQL错诣癿问题。

我们熟恲癿令牉验证、自劢验证和自劢完成(我们会在后面看刡相关癿用法)功能,其实都
必须通过create方法才能生效。Create方法创建癿数据对象是保存在内存中,幵没有实际写入刡数据库
中,直刡使用add戒者save方法。如果叧是想简单创建一个数据对象,幵丌需要完成一些额外癿功能
癿话,可以使用data方法简单癿创建数据对象。

 

setInc和setDec方法。对于统计字段(通常指的是数字类型)的更新:
$Model->setInc(‘score’,'id=5′,3); // 用户的积分加3
$Model->setInc(‘score’,'id=5′); // 用户的积分加1
$Model->setDec(‘score’,'id=5′,5); // 用户的积分减5
$Model->setDec(‘score’,'id=5′); // 用户的积分减1

D删除:

delete->()删除数据
$User->where(‘status=0′)->order(‘create_time’)->limit(’5′)->delete();

Model的其他常见方法:

order方法:结果排序 例如:
order(‘id desc’)
排序方法支持对多个字段的排序
order(‘status desc,id asc’)
order方法的参数支持字符串和数组,数组的用法如下:
order(array(‘status’=>’desc’,'id’))

limit方法:结果限制
limit(’1,10′)
如果使用limit(’10′) 等效于 limit(’0,10′)

page方法:查询分页,Page方法的用法和limit方法类似,格式为:
Page(‘page[,listRows]‘)
Page表示当前的页数,listRows表示每页显示的记录数。例如表示每页显示10条记录的情况下面,获取第2页的数据:
Page(’2,10′)
listRow如果不写的话,会读取limit(‘length’) 的值,例如表示每页显示25条记录的情况下面,获取第3页的数据:
limit(25)->page(3);
如果limit也没有设置的话,则默认为每页显示20条记录。

Join方法:查询Join支持.Join方法的参数支持字符串和数组,并且join方法是连贯操作中唯一可以多次调用的方法。例如:
$Model->join(‘ work ON artist.id = work.artist_id’)->join(‘card ON artist.card_id = card.id’)->select();
默认采用LEFT JOIN 方式,如果需要用其他的JOIN方式,可以改成
$Model->join(‘RIGHT JOIN work ON artist.id = work.artist_id’)->select();

Distinct方法:查询的Disiinct支持。查询数据的时候进行唯一过滤
$Model->Distinct(true)->select();

Relation方法:关联查询支持
$Model->Relation(true)->select();


条件查询

$map->put('name','php'); //name='php'

('name',array('like','think')); //name like '...'

('id',array('in',array(1,2,4)));

('id',array('10','3','or')); //id>=10 or

 


thinkphp多表查询语句 

1、table()函数
thinkphp中提供了一个table()函数,具体用法参考以下语句:
$list=$Demo->table('think_blog blog,think_type type')->where('blog.typeid=type.id')->field('blog.id as id,blog.title,blog.content,type.typename as type')->order('blog.id desc' )->limit(5)->select();
echo $Demo->getLastSql(); //打印一下SQL语句,查看一下
 
2、join()函数
看一下代码:
$Demo = M('artist');
$Demo->join('RIGHT JOIN think_work ON think_artist.id = think_work.artist_id' );
//可以使用INNER JOIN 或者 LEFT JOIN 这里一定要注意表名的前缀!
echo $Demo->getLastSql(); //打印一下SQL语句,查看一下

 

附最简单的增删查改的代码
[php] 
// 查询数据 
public function index(){ 
    $Form   = M("Form"); 
    $list   =   $Form->limit(5)->order('id desc')->findAll(); 
    $this->assign('list',$list); 
    $this->display(); 

// 写入数据 
public function insert() { 
    $Form   =   D("Form"); 
    if($vo = $Form->create()) { 
        $list=$Form->add(); 
        if($list!==false){ 
            $this->success('数据保存成功!'); 
        }else{ 
            $this->error('数据写入错误!'); 
        } 
    }else{ 
        $this->error($Form->getError()); 
    } 

 
// 更新数据 
public function update() { 
    $Form   =   D("Form"); 
    if($vo = $Form->create()) { 
        $list=$Form->save(); 
        if($list!==false){ 
            $this->success('数据更新成功!'); 
        }else{ 
            $this->error("没有更新任何数据!"); 
        } 
    }else{ 
        $this->error($Form->getError()); 
    } 

// 删除数据 
public function delete() { 
    if(!emptyempty($_POST['id'])) { 
        $Form   =   M("Form"); 
        $result =   $Form->delete($_POST['id']); 
        if(false !== $result) { 
            $this->ajaxReturn($_POST['id'],'删除成功!',1); 
        }else{ 
            $this->error('删除出错!'); 
        } 
    }else{ 
        $this->error('删除项不存在!'); 
    } 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

See all articles