关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

最为常用的Laravel操作(1)-Eloquent模型

发布时间:2023-07-01 00:28:34
快速入门 更换表名 protected $table = 'my_flights'; 更换主键名称 protected $primaryKey = 'id'; 注意: Eloquent 默认主键字段是自增的整型数据, 这意味着主键将会被自动转化为 int 类型, 如果你想要使用非自增或非数字类型主键, 必须在对应模型中设置 $incrementing` 属性为 `false` , 如果主键不是整型, 还要设置 `$keyType 属性值为 string. 关闭时间戳记录 public $timestamps = false; 获取模型数据 // Eloquent 的 all 方法返回模型表的所有结果 $flights = App\Flight::all(); foreach ({ mathJaxContainer[1]}flight) { echo $flight->name; } // 添加约束条件 $flights = App\Flight::where('active', 1) ->orderBy('name', 'desc') ->take(10) ->get(); 获取单个模型 // 通过主键获取模型 $flight = App\Flight::find(1); // 获取匹配查询条件的第一个模型 $flight = App\Flight::where('active', 1)->first(); // 通过传递主键数组来调用 find 方法, 这将会返回匹配记录集合 $flights = App\Flight::find([1, 2, 3]); 获取聚合结果 $count = App\Flight::where('active', 1)->count(); $max = App\Flight::where('active', 1)->max('price'); 插入记录 $flight = new Flight; { mathJaxContainer[2]}request->name; $flight->save(); 更新模型 $flight = App\Flight::find(1); $flight->name = 'New Flight Name'; $flight->save(); 批量更新 App\Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]); 删除模型 // 删除 $flight = App\Flight::find(1); $flight->delete(); // 通过主键删除模型 App\Flight::destroy(1); App\Flight::destroy([1, 2, 3]); App\Flight::destroy(1, 2, 3); // 通过查询删除模型 $deletedRows = App\Flight::where('active', 0)->delete(); 软删除 // Eloquent 模型 use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Flight extends Model { use SoftDeletes; /** * 应该被调整为日期的属性 * * @var array */ protected $dates = ['deleted_at']; } // 数据表结构添加 deleted_at 列 Schema::table('flights', function ($table) { $table->softDeletes(); }); // 判断给定模型实例是否被软删除, 可以使用 trashed 方法 if ($flight->trashed()) { // ... } // 查询被软删除的模型 $flights = App\Flight::withTrashed() ->where('account_id', 1) ->get(); $flight->history()->withTrashed()->get(); // 只获取软删除模型 $flights = App\Flight::onlyTrashed() ->where('airline_id', 1) ->get(); // 恢复软删除模型 $flight->restore(); // 使用 restore 方法来快速恢复多个模型, 不会触发任何模型事件 App\Flight::withTrashed() ->where('airline_id', 1) ->restore(); $flight->history()->restore(); 本地作用域 /** * 只包含活跃用户的查询作用域 * * @return \Illuminate\Database\Eloquent\Builder */ public function scopePopular($query) { return $query->where('votes', '>', 100); } /** * 只包含激活用户的查询作用域 * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeActive($query) { return $query->where('active', 1); } // 使用本地作用域 $users = App\User::popular()->active()->orderBy('created_at')->get(); 动态作用域 /** * 让查询只包含给定类型的用户 * * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $type * @return \Illuminate\Database\Eloquent\Builder */ public function scopeOfType({ mathJaxContainer[3]}type) { return { mathJaxContainer[4]}type); } // 使用动态作用域 $users = App\User::ofType('admin')->get(); 模型关联 一对一关联 // 拥有 class User extends Model { /** * 获取关联到用户的手机 */ public function phone() { // Phone : 关联的模型 // Phone : user_id 外键 // User : id 主键 return $this->hasOne('App\Phone', 'user_id', 'id'); } } // 所属 class Phone extends Model { /** * 获取拥有该手机的用户 */ public function user() { // User : 所属的模型 // Phone : user_id 外键 // User : id 父模型主键 return $this->belongsTo('App\User', 'user_id', 'id'); } } // 空模型 class Article extends Model { /** * 获取文章作者 */ public function user() { return { mathJaxContainer[5]}user) { $user->name = 'Guest Author'; }); } } 一对多关联 // 拥有 class Post extends Model { /** * 获取博客文章的评论 */ public function comments() { // Comment : 关联的模型 // Comment : post_id 外键 // Post : id 主键 return $this->hasMany('App\Comment', 'post_id', 'id'); } } // 所属 class Comment extends Model { /** * 获取评论对应的博客文章 */ public function post() { // Post : 关联的模型 // Comment : post_id 外键 // Post : id 父模型主键 return $this->belongsTo('App\Post', 'post_id', 'id'); } } 多对多关联 // 关联 class User extends Model { /** * 用户角色 */ public function roles() { // Role : 关联的模型 // user_roles : 中间表名称 // user_id : 对应到模型主键 // role_id : 对应到关联主键 return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id'); } } // 获取中间表字段, 通过 pivot 属性 $user = App\User::find(1); foreach ({ mathJaxContainer[6]}role) { echo $role->pivot->created_at; } // 当 pivot 表包含额外的属性时, 必须定义关联时先指定 return $this->belongsToMany('App\Role')->withPivot('column1', 'column2'); // 自动包含created_at 和 updated_at return $this->belongsToMany('App\Role')->withTimestamps(); // 更换 pivot 为 subscription, 提升可读性 return $this->belongsToMany('App\Podcast') ->as('subscription') ->withTimestamps(); $users = User::with('podcasts')->get(); foreach ({ mathJaxContainer[7]}podcast) { echo $podcast->subscription->created_at; } 渴求式加载 // select * from books $books = App\Book::all(); // select * from authors where id in (1, 2, 3, 4, 5, ...) $books = App\Book::with('author')->get(); foreach ({ mathJaxContainer[8]}book) { echo $book->author->name; } // 渴求式加载多个关联关系 $books = App\Book::with('author', 'publisher')->get(); // 嵌套的渴求式加载 $books = App\Book::with('author.contacts')->get(); // 渴求式加载指定字段 // 注: 使用这个特性时, id 字段是必须列出的 $users = App\Book::with('author:id,name')->get(); // 带条件约束的渴求式加载 { mathJaxContainer[9]}query) { $query->where('title', 'like', '%first%'); }])->get(); 插入 / 更新关联模型 // 插入关联模型 $comment = new App\Comment(['message' => 'A new comment.']); $post = App\Post::find(1); // 调用 comments 方法获取关联关系实例, save 将添加 post_id 到 Comment 模型中 { mathJaxContainer[10]}comment); // 保存多个关联模型 $post = App\Post::find(1); $post->comments()->saveMany([ new App\Comment(['message' => 'A new comment.']), new App\Comment(['message' => 'Another comment.']), ]); // 使用 create 创建, 与 save 不同的是, 它j接收一个关联数组, create 方法遵循模型属性的批量赋值操作 $post = App\Post::find(1); { mathJaxContainer[11]}post->comments()->create([ 'message' => 'A new comment.', ]); // 保存多个关联模型 $post = App\Post::find(1); $post->comments()->createMany([ [ 'message' => 'A new comment.', ], [ 'message' => 'Another new comment.', ], ]); // 更新从属关联关系 (belongsTo) $account = App\Account::find(10); // associate 方法会在子模型设置外键 { mathJaxContainer[12]}account); $user->save(); // 移除关联 (belongsTo) // dissociate 方法会设置关联关系的外键为 null $user->account()->dissociate(); $user->save(); 附加 / 分离多对多关联模型 $user = App\User::find(1); // 在连接模型的中间表中插入记录 { mathJaxContainer[13]}roleId); // 插入数据和附加的数组到中间表 { mathJaxContainer[14]}roleId, ['expires' => $expires]); // 从中间表中移除相应的记录: 指定用户移除某个角色 { mathJaxContainer[15]}roleId); // 从中间表中移除相应的记录: 指定用户移除所有角色 $user->roles()->detach(); // attach 和 detach 还接收数组形式的 ID 作为输入 $user = App\User::find(1); $user->roles()->detach([1, 2, 3]); $user->roles()->attach([ 1 => ['expires' => $expires], 2 => ['expires' => $expires] ]); 在中间表上保存额外数据 处理多对多关联时, save 方法接收中间表数组作为第二个参数: App\User::find(1)->roles()->save({ mathJaxContainer[16]}expires]); 访问器和修改器 访问器和修改器 允许你在获取模型属性或设置其值时格式化 Eloquent 属性. 例如, 你可能想要使用 Laravel 加密器对存储在数据库中的数据进行加密, 并且在 Eloquent 模型中访问时自动进行解密. 除了自定义访问器和修改器, Eloquent 还可以自动转换日期字段为 Carbon 实例甚至 将文本转换为 JSON . 访问器 class User extends Model { /** * 获取用户的名字 * * @param string $value * @return string */ public function getFirstNameAttribute($value) { return ucfirst($value); } /** * 获取用户的全名 * * @return string */ public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}"; } } // 访问 first_name 属性 $firstName = App\User::find(1)->first_name; 修改器 class User extends Model { /** * 设置用户的名字 * * @param string $value * @return string */ public function setFirstNameAttribute($value) { { mathJaxContainer[18]}value); } } // 设置 first_name 属性 App\User::find(1)->first_name = 'Sally'; 日期修改器 默认情况下, Eloquent 将会转化 created_at 和 updated_at 列的值为 Carbon 实例, 该类继承自 PHP 原生的 Datetime 类, 并提供了各种有用的方法. 你可以自定义哪些字段被自动调整修改, 甚至可以通过重写模型中的 $dates 属性完全禁止调整: class User extends Model { /** * 应该被调整为日期的属性 * * @var array */ protected $dates = [ 'created_at', 'updated_at', 'disabled_at' ]; } // 自动转换并存储到数据库中 $user = App\User::find(1); $user->disabled_at = Carbon::now(); $user->save(); // 使用 Carbon 提供的方法 $user = App\User::find(1); return $user->disabled_at->getTimestamp(); 模型日期格式 默认情况下, 时间戳的格式是 Y-m-d H:i:s , 可以结合 $dateFormat 属性自定义格式: class Flight extends Model { /** * 模型日期的存储格式 * * @var string */ protected $dateFormat = 'U'; } 属性转换 支持的转换类型: integer , real , float , double , string , boolean , object , array , collection , date , datetime 和 timestamp . 如果数据库有一个 JSON 或 TEXT 字段类型包含了序列化 JSON, 可使用 array 转换, 将自动进行 序列化 和 反序列化 . class User extends Model { /** * 应该被转化为原生类型的属性 * * @var array */ protected $casts = [ // 转换 is_admin 属性: 从 integer (0/1) 转换为 boolean 'is_admin' => 'boolean', // 访问 options 属性将会自动从 JSON 反序列化为 PHP 数组 // 设置 options 属性的值时, 给定数组将会自动转化为 JSON 以供存储 'options' => 'array', ]; } // is_admin 属性已经被转换了: if ($user->is_admin) { // } // 自动序列化和反序列化 $user = App\User::find(1); { mathJaxContainer[19]}user->options; $options['key'] = 'value'; { mathJaxContainer[20]}options; $user->save(); 文章来源于本人博客,发布于 2018-06-02,原文链接:https://imlht.com/archives/152/

/template/Home/leiyu/PC/Static