Laravel模型类&DB类操作数据库

一、使用DB类操作数据库

配置好数据库连接后,就可以使用DB类来运行查询。DB类为每种查询提供了相应方法:select, update, insert, delete和statement。

1、运行原生sql查询

注意:原生sql语句中的数据表名,必须是包含前缀的完整表名。

-> 运行 select/insert/update/delete 查询
$results = DB::select('select * from users where id = ?', [1]);

select方法以数组的形式返回结果集,数组中的每一个结果都是一个PHP StdClass对象,从而允许你像下面这样访问结果值:

foreach ($results as $user) {
    echo $user->name;
}
-> 运行一个通用语句

有些数据库语句不返回任何值,对于这种类型的操作,可以使用DB类的statement方法:该方法返回布尔值true或false,代表语句执行成功或失败。

DB::statement('drop table users');

2、查询构建器

指定操作的数据表:

DB::table(表名);

注:查询构建器中table方法中的表名,是不包含前缀的表名。

-> 查询数据

①获取多条数据–get方法

$users = DB::table('users')->where('name', 'John')->get();

get方法返回包含结果集的Illuminate\Support\Collection,其中每一个结果都是PHP的StdClass对象实例。你可以像访问对象的属性一样访问字段的值:

foreach ($users as $user) {
    echo $user->name;
}

②获取一条数据–first方法
如果你只是想要从数据表中获取一行数据,可以使用first方法,该方法将会返回单个StdClass对象:

$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;

注:根据主键获取一条数据–find方法
如果你想要根据主键值从数据表中获取数据,可以使用find方法(必须传递参数):

//传递一个主键值,获取一条数据
$user = DB::table('users')->find(1);

③聚合查询(统计查询)
查询构建器还提供了多个聚合方法,如count, max, min, avg和 sum,你可以在构造查询之后调用这些方法:

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');

④select子句–select方法
当然,我们并不总是想要获取数据表的所有列,使用select方法,你可以为查询指定自定义的select子句:

$users = DB::table('users')->select('name', 'email as user_email')->get();

⑤where子句–where方法

$users = DB::table('users')
            ->where('votes', '>=', 100)
            ->get();
$users = DB::table('users')
            ->where('votes', '<>', 100)
            ->get();
$users = DB::table('users')
            ->where('name', 'like', 'T%')
            ->get();

还可以传递条件数组到where函数:

$users = DB::table('users')->where(['id'=>'1'])->get();
$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();
-> 插入数据
DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0]
]);

自增ID
如果数据表有自增ID,使用insertGetId方法来插入记录并返回ID值:

$id = DB::table('users')->insertGetId(
    ['email' => '[email protected]', 'votes' => 0]
);
-> 更新数据
DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);
这两个方法都至少接收一个参数:需要修改的列。第二个参数是可选的,用于控制列值增加/减少的数目。
DB::table('users')->increment('votes');
DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes');
DB::table('users')->decrement('votes', 5);
-> 删除数据

查询构建器还可以通过delete方法从表中删除记录:

DB::table('users')->delete();
DB::table('users')->where('votes', '>', 100)->delete();

清除整张表,也就是删除所有列并将自增ID置为0,可以使用truncate方法:

DB::table('users')->truncate();

二、模型中的数据操作

增删改查 (CURD : create update read delete)

Eloquent模型本身是一个功能强大的查询构建器,可以通过模型调用DB类查询构建器中的方法。模型本身也封装了一些自己的方法,用于进行数据查询、插入、更新、删除等操作。

1、查询一条数据

①调用find方法(必须传递参数)

// 通过主键获取一条数据...
$manager = Manager::find(1);

②调用first方法(不需要传递参数)

// 获取匹配查询条件的第一条数据...
$manager = Manager::where('active', 1)->first();

注:通过模型调用find方法和first方法,返回值都是一个包含数据的模型对象。这个对象可以当做数组来用,也可以调用toArray方法直接转化为数组。

// 通过主键获取一条数据...
$manager = Manager::find(1)->toArray();

2、查询多条数据(推荐get方法)

①调用模型本身的all方法

//调用模型的all方法 查询所有数据
$managers = Manager::all();
//可以传递参数,指定要查询的字段
$managers = Manager::all('id', 'username');
或者 传递数组格式的字段参数
$managers = Manager::all(['id', 'username']);

注:all方法是模型本身封装的一个静态方法,只能直接调用,前面不能调用where等方法。
②调用find方法
还可以通过传递主键数组来调用find方法,这将会返回匹配记录集合:

//根据主键数组查询多条数据
$managers = Manager::find([1, 2, 3]);

③调用get方法(推荐)

//根据条件查询数据
$managers = Manager::where('status', 1)->get();

注:查询多条数据,返回的是一个包含模型对象的数据集合。

3、添加数据

可以通过模型调用查询构建器的insert方法进行添加数据操作,这里主要介绍模型的方法。

-> 静态create方法添加数据

可以静态调用create方法,传递数据数组,进行批量字段复制并添加。
使用create方法之前,必须先在模型中定义哪些属性是可以进行赋值的,使用模型上的$fillable属性即可实现。

控制器中调用模型的create方法:

$data = ['username' => 'admin100', 'status' => 1];
$manager = Manager::create($data);
$id = $manager->id;

create方法返回包含了插入数据的模型对象本身。

-> save方法添加数据(不推荐)
$manager = new Manager;
$manager->username = 'admin100';
$manager->save();

save方法返回值:成功时返回true,失败时返回false。
添加成功后,可以通过模型调用id属性,获取添加记录的主键值。

$id = $manager->id;

4、修改数据

-> update方法修改数据

通常还可以调用查询构建器的update方法同时修改满足条件的一条或多条数据。

//根据条件更新数据
$manager = Manager::where('id', 1)->update(['status' => 1]);
-> save方法修改数据(不推荐)

模型的save方法还可以用于更新数据表已存在的数据。

//先查询到要修改的数据
$manager = Manager::find(1);
//设置想要更新的属性
$manager->email = '[email protected]' ;
//调用save方法
$manager->save();

5、删除数据(推荐destroy方法)

-> 模型本身的delete方法删除数据

//先查询到要删除的数据
$manager = Manager::find(2);
//调用delete方法
$manager->delete();

-> 模型本身的静态destroy方法删除数据

//根据主键id删除一条数据
Manager::destroy(2);
//根据多个主键id批量删除数据
Manager::destroy([2,3]);
Manager::destroy(2,3);

-> 查询构建器的delete方法删除数据
可以根据where条件,直接调用查询构建器的delete方法,删除满足条件的数据

//先查询到要删除的数据
Manager::where('id', 2)->delete();

6、软删除

-> 软删除

要启用模型的软删除功能,可以使用模型上的Illuminate\Database\Eloquent\SoftDeletes这个trait :

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
//引入SoftDeletes 这个trait
use Illuminate\Database\Eloquent\SoftDeletes;

class Manager extends Model{
    //SoftDeletes 这个trait
use SoftDeletes;
//指定软删除字段名称
    protected $dates = ['deleted_at'];
}

进行以上设置后,调用模型本身的delete方法和destroy方法删除数据,都会进行软删除。
deleted_at列将被设置为当前日期和时间,并且,当查询一个使用软删除的模型时,被软删除的模型将会自动从查询结果中排除。

-> 查询被软删除的数据

被软删除数据将会自动从查询结果中排除,但是,如果你想要被软删除的数据出现在查询结果中,可以使用withTrashed方法:

$managers = Manager::withTrashed()->get();

也可以使用onlyTrashed方法只获取软删除数据:

$managers = Manager::onlyTrashed()->get();
-> 恢复被软删除的数据

有时候你希望恢复一个被软删除的模型,可以使用restore方法:

$manager = Manager::withTrashed()->first();
$manager->restore();

你还可以在查询中使用restore方法来快速恢复多个模型:

Manager::withTrashed()
        ->where('id', '>', 1)
        ->restore();
-> 永久删除数据

有时候你真的需要从数据库中删除一个模型,可以使用forceDelete方法:

// 强制删除单个模型实例...
$manager = Manager::find(1);
$manager->forceDelete();

三、where方法详解

-> 简单的where子句
//完整语法
where('字段名', '表达式', '查询条件')
//表达式为 等于号,可以省略不写。
where('字段名',  '查询条件')
//用法
$managers = Manager::where('id', '>', 3)->get();

-> or语句

你可以通过方法链将多个where约束链接到一起,也可以添加or子句到查询,orWhere方法和where方法接收参数一样:

$managers = Manager::where('id', '>', 3)
                    ->orWhere('status', 1)
                    ->get();
-> 批量条件
$users = DB::table('users')->where(['id'=>'1'])->get();
$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();
//基本语法
where(['字段名'=> '字段值'])
where([['字段名', '比较表达式', '字段值'],['字段名', '比较表达式', '字段值']])
-> 更多where子句

whereBetween
whereBetween方法验证列值是否在给定值之间:

$users = DB::table('users')->whereBetween('votes', [1, 100])->get();

whereNotBetween
whereNotBetween方法验证列值不在给定值之间:

$users = DB::table('users')->whereNotBetween('votes', [1, 100])->get();

whereIn/whereNotIn
whereIn方法验证给定列的值是否在给定数组中:

$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();

whereNotIn方法验证给定列的值不在给定数组中:

$users = DB::table('users')->whereNotIn('id', [1, 2, 3])->get();

whereNull/whereNotNull
whereNull方法验证给定列的值为NULL:

$users = DB::table('users')->whereNull('updated_at') ->get();

whereNotNull方法验证给定列的值不是NULL:

$users = DB::table('users')->whereNotNull('updated_at')->get();

whereDate / whereMonth / whereDay / whereYear
whereDate方法用于比较字段值和日期:

$users = DB::table('users')->whereDate('created_at', '2016-10-10')->get();

whereMonth方法用于比较字段值和一年中的指定月份:

$users = DB::table('users')->whereMonth('created_at', '10')->get();

whereDay方法用于比较字段值和一月中的制定天:

$users = DB::table('users')->whereDay('created_at', '10')->get();

whereYear方法用于比较字段值和指定年:

$users = DB::table('users')->whereYear('created_at', '2016')->get();

whereColumn
whereColumn方法用于验证两个字段是否相等:

$users = DB::table('users')->whereColumn('first_name', 'last_name')->get();

还可以传递一个比较运算符到该方法:

$users = DB::table('users')->whereColumn('updated_at', '>', 'created_at')
            ->get();

还可以传递多条件数组到whereColumn方法,这些条件通过and操作符进行连接:

$users = DB::table('users')
            ->whereColumn([
                ['first_name', '=', 'last_name'],
                ['updated_at', '>', 'created_at']
            ])->get();

猜你喜欢

转载自blog.csdn.net/csdn_heshangzhou/article/details/83034324