博客
关于我
laravel5.5之模型操作数据库 — Eloquent ORM(实践)
阅读量:792 次
发布时间:2023-01-30

本文共 2768 字,大约阅读时间需要 9 分钟。

Laravel模型操作实用指南

在Laravel的开发过程中,你很快就会接触到Eloquent ORM,这是Laravel官方提供的数据库 ORM框架,支持通过模型和关系来简化数据库操作。以下是一些实用的模型操作技巧,帮助你更高效地进行数据库开发。

一、背景

Laravel支持三种方式操作数据库:原生SQL、构造器查询和Eloquent ORM。前两种方式较为基础,本文主要围绕Eloquent ORM展开,因为其提供的模型操作方式最为方便和灵活。

二、模型管理配置

在实际开发中,模型文件的管理既是必然也是重要的一步。你应该将模型文件统一存放在/app/Models文件夹下。例如,系统默认已经在这个目录下提供了User模型文件,因此如果需要自定义,可以根据需求在Models文件夹下新建相应的模型文件。

1.1 创建模型文件

使用 artisan工具生成新模型文件,可以执行以下命令:

php artisan make:model Models\User

二、模型代码配置

模型类通常包括以下几个关键属性:

namespace App\Models;use Illuminate\Database\Eloquent\Model;class User extends Model{    protected $table = 'users'; // 指定表名    protected $primaryKey = 'id'; // 主键字段,默认使用'id'作为主键    protected $timestamps = true; // 是否包含created_at和updated_at字段    protected $dateFormat = 'Y-m-d H:i:s'; // 定制日期格式    protected $fillable = ['name', 'sex', 'age', 'pwd']; // 可填充字段数组    protected $guarded = ['id']; // 不可修改的字段数组}

三、基本数据操作

3.1 数据录入

要对数据库进行数据插入,可以使用以下两种方式:

方式一:手动插入

$user = new User;$user->name = '张三';$user->pwd = '123';$user->save();

方式二:使用create方法

return User::create([    'name' => '李四',    'sex' => 1,    'age' => 23,    'pwd' => '456']);

方式三:批量插入

config/app.php中需要加载DB辅助类,并在需要使用时引入:

use DB;...public function __construct(){    $this->db = DB::getInstance();}

批量插入数据:

DB::table('users')->insert([    ['name' => '用户1'],    ['name' => '用户2'],    // 其他数据]);

3.2 数据更新

单条数据更新

public function update(Request $request){    $data = $request->validate([        'id' => 'required',    ]);    $user = User::find($data['id']);    if (!empty($map = $request->except('id'))) {        foreach ($map as $k => $v) {            $user->$k = $v;        }        $result = $user->save();        return $result;    }    return '无更新任何数据';}

批量更新

如果需要根据条件更新数据,可以按照以下方式实现:

User::where('age', 'gt', 30)    ->update(['name' => 'newName']);

三、块查询优化

在处理大批量数据时,直接遍历所有数据的做法可能会导致性能问题。Eloquent提供了chunk方法,允许你按块处理数据。

普通遍历与块查询对比

// 普通遍历$users = User::all();foreach ($users as $user) {    $user->update(['sex' => 1]);}// 按块处理User::chunk(100, function ($users) {    foreach ($users as $user) {        $user->update(['sex' => 1]);    }});

四、软删除操作

在实际开发中,软删除可以避免物理删除数据带来的问题。为了实现软删除,你需要:

  • 在模型中引入SoftDeletes类:
  • namespace App\Models;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\SoftDeletes;class User extends Model{    use SoftDeletes;    protected $dates = ['deleted_at'];    // 可填充字段...}
    1. 使用迁移添加deleted_at字段:
    2. php artisan make:migration add_deleted_at_to_users_table
      1. 在迁移文件中执行:
      2. public function up(){    Schema::table('users', function ($table) {        $table->softDeletes();    });}

        五、数据库操作示例

        5.1 判断记录状态

        $user = User::find(1);if ($user->trashed()) {    // 判断该记录是否已被软删除}

        5.2 恢复被软删除的记录

        $user = User::find(1);$user->restore();

        5.3 执行强制删除

        $user = User::find(1);$user->forceDelete();

        通过以上方法,你可以灵活地进行数据库操作,同时充分利用Eloquent ORM的高级功能,提高开发效率。

    转载地址:http://ufgyk.baihongyu.com/

    你可能感兴趣的文章
    Learning English With Our Team
    查看>>
    Learning jQuery, 4th Edition 勘误表
    查看>>
    Learning Perl 学习笔记
    查看>>
    Learning Python 008 正则表达式-001
    查看>>
    Learning to act by predicting the future
    查看>>
    Learning XNA 4.0 第三章(结尾)
    查看>>
    Leedcode12-word-break-i
    查看>>
    Leedcode2-后缀表达式结果
    查看>>
    Leedcode3- Max Points on a Line 共线点个数
    查看>>
    Leedcode4-sort listnode 归并排序
    查看>>
    Leedcode5-Sort a linked list using insertion sort.
    查看>>
    Leedcode6-binary-tree-preorder-traversal
    查看>>
    Leedcode7-binary-tree-postorder-traversal
    查看>>
    Leedcode8-reorder-list
    查看>>
    Leedcode9-linked-list-cycle-i
    查看>>
    LeetCode - 50. Pow(x, n)
    查看>>
    Leetcode - Permutations I,II
    查看>>
    LeetCode 122. Best Time to Buy and Sell Stock II
    查看>>
    Leetcode 146. LRU 缓存。 手撕lru? 面试官让手写lru?java版本lru
    查看>>
    LeetCode 15. 3Sum
    查看>>