search
HomeBackend DevelopmentPHP TutorialHow does Laravel operate the database? Three ways to operate Laravel database (code)

Laravel is a PHP Web development framework (PHP Web Framework). It can free you from messy code; it can help you build a perfect network APP, and every line of code can be concise and expressive. So, how does the laravel framework operate the database? Please take a look at the specific content.

Laravel provides 3 ways to operate the database: DB facade (original way), query builder and Eloquent ORM.

#The database configuration file is in database.php in the config directory. Open this file and find the configuration items of mysql.


#There is an env here, which actually calls laravel The .env file in the root directory, this file stores Laravel database configuration information. Open it. Just modify it to the database information of the project.


## Please create a database by yourself, which must contain vipinfo table and insert some data for easy use below. The structure of the table is as shown below.

As the name suggests: this table is a membership table, with member ID (primary key), member name, and member type. Member points and other fields.

1.

DB facade for database operations

# In app->Http->Controllers Create a new

Student controller, StudentController.php in the directory. StudentController.php code is as follows:

<?php 
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;class StudentController extends Controller {
 
}

1 .laravel database query Add a test1 method in the Student controller. The query uses the static method select() of the DB class, and the parameters are native sql statement, returns a two-dimensional array. dd() is a method provided by laravel, which can display an array in the form of a node tree. The specific code is as follows:

public function test1()
{
    $student=DB::select("select * from vipinfo");    //返回一个二维数组  
    $student    var_dump($student);        //以节点树的形式输出结果    
    dd($student);
}

Route configuration:

Route::get('test1',['uses'=>'StudentController @test1']);


URL access: http://localhost/

l

aravel/public/index.php/test1 , will print out the result.

## 2. New operation

The newly used static method insert() of the DB class is used. The first parameter is the sql statement, and the second parameter is an array. The data to be inserted is placed in the array. here? It is a placeholder that prevents SQL injection through the database interface layer pdo. What is returned is the result of execution. Returns true if the insertion is successful, otherwise false.
##

public function test1()
{
    $student=DB::select("select * from vipinfo");    //返回一个二维数组  
    $student    var_dump($student);        //以节点树的形式输出结果    
    dd($student);
}

##3. Update operation

The update uses the static method update() of the DB class. The first parameter is the sql statement, and the second parameter is an array. The elements respectively correspond to the question marks in the sql statement. Returns true if the update is successful.

    $bool=DB::update('update vipinfo set vip_fenshu= ? where vip_ID= ? ',[700,5]);
    var_dump($bool);  //更新成功返回true

4. Delete operation

删除使用的是DB类的静态方法delete(),第一个参数是sql语句,第二个参数是一个数组,数组里的元素分别对应sql语句里的问号。返回的是删除的行数。

    $num=DB::delete(&#39;delete from vipinfo where vip_ID= ?&#39;,[5]);
    echo $num;

二、数据库操作之查询构造器

laravel查询构造器提供了方便流畅的接口,用来建立及执行数据库查找语法。使用了pdo参数绑定,使应用程序免于sql注入,因此传入的参数不需要额外转义特殊字符。基本上可以满足所有的数据库操作,而且在所有支持的数据库系统上都可以执行。

1.使用查询构造器实现增删改查

同样在Student控制器里测试以下代码:

(1)新增

    $bool=DB::table("vipinfo")->insert([&#39;vip_ID&#39;=>6,&#39;vip_name&#39;=>&#39;zls&#39;,&#39;vip_type&#39;=>"出行",&#39;vip_fenshu&#39;=>800]);
    echo $bool; //返回bool值
    //如果想得到新增的id,则使用insertGetId方法
    $id=DB::table("vipinfo")->insertGetId([&#39;vip_ID&#39;=>5,&#39;vip_name&#39;=>&#39;wyp&#39;,&#39;vip_type&#39;=>"出行",&#39;vip_fenshu&#39;=>800]);
    echo $id;
    //插入多条数据
    $bool=DB::table("vipinfo")->insert([
    [&#39;vip_ID&#39;=>5,&#39;vip_name&#39;=>&#39;wyp&#39;,&#39;vip_type&#39;=>"出行",&#39;vip_fenshu&#39;=>800],
    [&#39;vip_ID&#39;=>6,&#39;vip_name&#39;=>&#39;zls&#39;,&#39;vip_type&#39;=>"出行",&#39;vip_fenshu&#39;=>800],
    ]);
    echo $bool; //返回bool值

(2)修改

$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->update([&#39;vip_fenshu&#39;=>500]);
echo $bool;
//自增
$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->increment("vip_fenshu");//自增1
$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->increment("vip_fenshu",3);//自增3
echo $bool;
//自减
$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->decrement("vip_fenshu");//自1
$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->decrement("vip_fenshu",3);//自增3
echo $bool;
//自增时再修改其他字段
$bool=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->increment("vip_fenshu",3,[&#39;vip_name&#39;=>&#39;dbdibi&#39;]);//自增3

(3)删除

$num=DB::table("vipinfo")->where(&#39;vip_ID&#39;,6)->delete();//删除1条
$num=DB::table("vipinfo")->where(&#39;vip_ID&#39;,&#39;>&#39;,4)->delete();//删除多条
echo $num;  //删除的行数
$num=DB::table("vipinfo")->truncate();//删除整表,不能恢复,谨慎使用

(4)查询

//get()返回多条数据
$student=DB::table("vipinfo")->get();
 var_dump($student);  
//first()返回1条数据
$student=DB::table("vipinfo")->first();  //结果集第一条记录
$student=DB::table("vipinfo")->orderBy(&#39;vip_ID&#39;,&#39;desc&#39;)->first();//按vip_ID倒序排序
var_dump($student);  
//where()条件查询
$student=DB::table("vipinfo")->where(&#39;vip_ID&#39;,&#39;>=&#39;,2)->get(); //一个条件   
$student=DB::table("vipinfo")->whereRaw(&#39;vip_ID> ? and vip_fenshu >= ?&#39;,[2,300])->get(); //多个条件
dd($student);
//pluck()指定字段,后面不加get
$student=DB::table("vipinfo")->pluck(&#39;vip_name&#39;);
dd($student);
//lists()指定字段,可以指定某个字段作为下标
$student=DB::table("vipinfo")->lists(&#39;vip_name&#39;,&#39;vip_ID&#39;);   //指定vip_ID为下标
dd($student);
$student=DB::table("vipinfo")->lists(&#39;vip_name&#39;);   //不指定下标,默认下标从0开始
//select()指定某个字段
$student=DB::table("vipinfo")->select(&#39;vip_name&#39;,&#39;vip_ID&#39;)->get();
dd($student);
//chunk()每次查n条
$student=DB::table("vipinfo")->chunk(2,function($students){  //每次查2条
    var_dump($students);
    if(.......) return false;  //在满足某个条件下使用return就不会再往下查了
});

2.使用聚合函数

//count()统计记录条数$nums=DB::table("vipinfo")->count();
echo $nums;//max()某个字段的最大值,同理min是最小值$max=DB::table("vipinfo")->max("vip_fenshu");
echo $max;//avg()某个字段的平均值$avg=DB::table("vipinfo")->avg("vip_fenshu");
echo $avg;//sum()某个字段的和$sum=DB::table("vipinfo")->sum("vip_fenshu");
echo $sum;

四、数据库操作之 - Eloquent ORM 

1.简介、模型的建立及查询数据

简介:laravel所自带的Eloquent ORM 是一个ActiveRecord实现,用于数据库操作。每个数据表都有一个与之对应的模型,用于数据表交互。

建立模型,在app目录下建立一个Student模型,即Student.php,不需要带任何后缀。

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model{
    //指定表名
protected $table= &#39;vipinfo&#39;;
//指定主键
protected $primaryKey= &#39;vip_ID&#39;;
}

在Student控制器里增加一个test3方法,配置路由Route::get('test3',['uses'=>'StudentController@test3']);

public function test3(){// all()方法查询所有数据$studnets=Student::all();
dd($studnets);//find()查询一条,依据主键查询。findOrFail()查找不存在的记录时会抛出异常
$student=Student::find(5);  //主键为5的记录
var_dump($student[&#39;attributes&#39;]);//查询构造器的使用,省略了指定表名
$student=Student::get();  
var_dump($student);
}

2 . 新增数据、自定义时间戳、批量赋值

(1)使用save方法新增

laravel会默认维护created_at,updated_at 两个字段,这两个字段都是存储时间戳,整型11位的,因此使用时需要在数据库添加这两个字段。如果不需要这个功能,只需要在模型里加一个属性:public $timestamps=false; 以及一个方法,可以将当前时间戳存到数据库

    protected function getDateFormat(){    
    return time();
    }

这样就不需要那两个字段了。

控制器里写:

    $student=new Student();    //设定数据
    $student->vip_name=&#39;xiaoming&#39;;
    $student->vip_type=&#39;出行&#39;;
    $student->vip_fenshu=900;
    $bool=$student->save(); //保存
    echo $bool;

从数据库里取得某条记录的时间戳时,默认取得的是按日期格式化好的时间戳,如果想取得原本的时间戳,则在模型里增加asDateTime方法。

    protected function asDateTime($val){    
    return $val;
    }

(2)使用create方法新增时,需要在模型里增加:

protected $fillable=[&#39;vip_name&#39;,&#39;vip_fenshu&#39;,&#39;vip_type&#39;];   //允许批量赋值的字段

 控制器里写:

Student::create([&#39;vip_name&#39;=>&#39;mmm&#39;,&#39;vip_fenshu&#39;=>999,&#39;vip_type&#39;=>&#39;出行&#39;]);

这样即可新增成功!

(3)firstOrCreate()以属性查找记录,若没有则新增

    $student=Student::firstOrCreate([&#39;vip_name&#39;=>&#39;mmm&#39;]);
    echo $student;

(4)firstOrNew()以属性查找记录,若没有则会创建新的实例。若需要保存,则自己调用save方法()

    $student=Student::firstOrNew([&#39;vip_name&#39;=>&#39;mmm&#39;]);
    $student->save();
    echo $student;

3.  修改数据

    //通过模型更新数据
    $student=Student::find(2);
    $student->vip_fenshu=10000;
    $student->save(); //返回bool值
    //通过查询构造器更新
    $num=Student::where(&#39;vip_ID&#39;,&#39;>&#39;,2)->update([&#39;vip_fenshu&#39;=>2000]);
    echo $num; //返回更新的行数

4.  删除数据

    //(1)通过模型删除数据
    $student=Student::find(11);
    $student->delete(); //返回bool值
    //(2)通过主键删除
    $num=Student::destroy(10); //删除主键为10的一条记录
    echo $num; //返回删除的行数
    $num=Student::destroy(10,5); //删除多条 或者$num=Student::destroy([10,5]);
    echo $num; //返回删除的行数

 相关推荐:

Laravel框架数据库CURD操作、连贯操作使用方法

Laravel教程之基础入门和如何操作数据库

The above is the detailed content of How does Laravel operate the database? Three ways to operate Laravel database (code). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),