Table of Contents
thinkphp多表查询语句
Home Backend Development PHP Tutorial ThinkPHP的CURD步骤及查询方法一览

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

Jun 13, 2016 am 10:45 AM
gt nbsp quot select string

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

所谓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'] = [email protected];
$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] view plaincopy
  1. // 查询数据  
  2. public function index(){  
  3.     $Form   = M("Form");  
  4.     $list   =   $Form->limit(5)->order('id desc')->findAll();  
  5.     $this->assign('list',$list);  
  6.     $this->display();  
  7. }  
  8. // 写入数据  
  9. public function insert() {  
  10.     $Form   =   D("Form");  
  11.     if($vo = $Form->create()) {  
  12.         $list=$Form->add();  
  13.         if($list!==false){  
  14.             $this->success('数据保存成功!');  
  15.         }else{  
  16.             $this->error('数据写入错误!');  
  17.         }  
  18.     }else{  
  19.         $this->error($Form->getError());  
  20.     }  
  21. }  
  22.   
  23. // 更新数据  
  24. public function update() {  
  25.     $Form   =   D("Form");  
  26.     if($vo = $Form->create()) {  
  27.         $list=$Form->save();  
  28.         if($list!==false){  
  29.             $this->success('数据更新成功!');  
  30.         }else{  
  31.             $this->error("没有更新任何数据!");  
  32.         }  
  33.     }else{  
  34.         $this->error($Form->getError());  
  35.     }  
  36. }  
  37. // 删除数据  
  38. public function delete() {  
  39.     if(!emptyempty($_POST['id'])) {  
  40.         $Form   =   M("Form");  
  41.         $result =   $Form->delete($_POST['id']);  
  42.         if(false !== $result) {  
  43.             $this->ajaxReturn($_POST['id'],'删除成功!',1);  
  44.         }else{  
  45.             $this->error('删除出错!');  
  46.         }  
  47.     }else{  
  48.         $this->error('删除项不存在!');  
  49.     }  


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

See all articles