【PHP】laravel 操作数据库

数据库

一、Eloquent 模型

查询

检索单个模型/集合

// 通过主键取回一个模型…

$flight = App\Flight::find(1);

// 取回符合查询限制的第一个模型…

$flight = App\Flight::where('active', 1)->first();

你也可以使用主键数组作为参数调用 find 方法,它将返回匹配记录的集合:

$flights = App\Flight::find([1, 2, 3]);

『找不到』异常
如果没有对异常进行捕获,则会自动返回 404 页面

$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();

聚合函数
提供了各种聚合方法,例如 count, max, min, avg, 和 sum。

$count = App\Flight::where('active', 1)->count();
$max = App\Flight::where('active', 1)->max('price');

cursor 使用游标来遍历数据库数据

foreach (Flight::where('foo', 'bar')->cursor() as $flight) {
    //
}

插入

先创建模型实例,再设置实例属性,然后调用 save 方法

$flight = new Flight;
$flight->name = $request->name;
$flight->save();

create 批量插入
在使用create之前,你需要先在模型上指定 fillable 或 guarded 属性,因为所有的 Eloquent 模型在默认情况下都不能进行批量赋值

$flight = App\Flight::create(['name' => 'Flight 10']);

更新

$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

批量更新
active等于1的数据都更新

App\Flight::where('active', 1)
          ->update(['delayed' => 1]);

删除

可以在模型示例上调用 delete 方法来删除模型。通过检索模型存在则删除

$flight = App\Flight::find(1);
$flight->delete();

通过主键删除模型
如果你已经知道了这个模型的主键,则可以删除模型而不检索它。此时,可以调用 destroy 方法:

App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);

通过查询删除模型

$deletedRows = App\Flight::where('active', 0)->delete();

软删除
开启模型的软删除功能,可以在模型上使用 Illuminate\Database\Eloquent\SoftDeletes trait 并把 deleted_at 字段加入 $dates 属性

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
    use SoftDeletes;
     //需要转换成日期的属性
    protected $dates = ['deleted_at'];
}

查询软删除模型

$flights = App\Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

二、DB facade 数据库

查询构造器

从数据表中获取所有行

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

从数据表中获取单行或列

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

使用 value 方法从记录中获取单个值

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

获取一列的值

$titles = DB::table('roles')->pluck('title');
$roles = DB::table('roles')->pluck('title', 'name');  // 定义键值

分块结果
一次处理 users 表中的 100 条记录

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

Selects 语句来查询指定的字段:

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

distinct 去重,允许你强制让查询返回不重复的结果:

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

原生方法
有时候你可能需要在查询中使用原生表达式。你可以使用 selectRaw 方法

$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();

或者
可以使用 whereRaw 和 orWhereRaw 方法将原生的 where 注入到你的查询中。

$orders = DB::table('orders')
                ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
                ->get();

其他 Where 语句


whereBetween 方法验证字段的值位于两个值之间:

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

whereNotBetween 方法验证字段的值位于两个值之外:

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

whereIn 方法验证字段的值在指定的数组内:

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

whereNotIn 方法验证字段的值 不 在指定的数组内:

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

whereNull 方法验证字段的值为 NULL:

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

whereNotNull 方法验证字段的值不为 NULL:

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

whereDate 方法用于比较字段的值和日期:

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

whereMonth 方法用于比较字段的值与一年的特定月份:

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

whereDay 方法用于比较字段的值与一个月的特定日期:

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

whereYear 方法用于比较字段的值与特定年份:

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

whereTime 用于将字段的值与特定的时间进行比较:

$users = DB::table('users')
                ->whereTime('created_at', '=', '11:20')
                ->get();

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();

orderBy 方法允许你通过给定字段对结果集进行排序。 orderBy 的第一个参数应该是你希望排序的字段,第二个参数控制排序的方向,可以是 asc 或 desc:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();

插入

查询构造器还提供了 insert 方法用于插入记录到数据库中。 insert 方法接收数组形式的字段名和字段值进行插入操作:

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

你还可以在 insert 中传入一个嵌套数组向表中插入多条记录。每个数组代表要插入表中的行:

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

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

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

更新

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

自增与自减
查询构造器还为给定字段的递增或递减提供了方便的方法。 此方法提供了一个比手动编写 update 语句更具表达力且更精练的接口。

DB::table('users')->increment('votes', 5);
DB::table('users')->decrement('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);

Deletes

查询构造器也可以使用 delete 方法从数据表中删除记录。在使用 delete 前,可添加 where 子句来约束 delete 语法:

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

三、分页

「简单分页」
显示简单的「下一页」和「上一页」的链接

$users = DB::table('users')->simplePaginate(15);

Eloquent 模型分页

$users = App\User::paginate(15);

显示分页结果

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>
{{ $users->links() }}

分页器实例方法
每个分页器实例可以通过以下方法获取额外的分页信息:

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (使用 simplePaginate 时不可用)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (使用 simplePaginate 时不可用)
$results->url($page)

四、验证

使用 Illuminate\Http\Request 对象提供的 validate 方法 。
如果验证通过,你的代码就可以正常的运行。但是如果验证失败,就会抛出异常,并自动将对应的错误响应返回给用户。在典型的 HTTP 请求的情况下,会生成一个重定向响应,而对于 AJAX 请求则会发送 JSON 响应。

  $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

数组数据的注意事项
如果你的 HTTP 请求包含一个 「嵌套」 参数(即数组),那你可以在验证规则中通过 「点」 语法来指定这些参数。

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

显示验证错误信息

@if ($errors->any())
    <div class="alert alert-default-danger">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">&times;</button>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </div>
@endif

查看特定字段的第一个错误消息
如果要查看特定字段的第一个错误消息,可以使用 first 方法:

$errors = $validator->errors();
echo $errors->first('email');

查看特定字段的所有错误消息
如果你想以数组的形式获取指定字段的所有错误消息,则可以使用 get 方法:

foreach ($errors->get('email') as $message) {
    //
}

判断特定字段是否含有错误消息
可以使用 has 方法来检测一个给定的字段是否存在错误消息:

if ($errors->has('email')) {
    //
}

在语言文件中指定自定义属性
如果要使用自定义属性名称替换验证消息的 :attribute 部分,就在 resources/lang/xx/validation.php 语言文件的 attributes 数组中指定自定义名称:

'attributes' => [
    'email' => 'email address',
],

五、定义Model

定义表名

protected $table = 'my_flights';

主键

protected $primaryKey ='';

时间戳(关闭自动写入时间戳)

public $timestamps = false;

可以作为批量赋值的『白名单』

protected $fillable = ['price'];

不允许被批量赋值的数组『黑名单』,将 $guarded 定义为空数组,则所有属性都可以被批量赋值

protected $guarded  =['price'];

参考来源
Laravel 5.6 中文文档

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值