laravel 之 Eloquent 模型修改器和序列化示例

修改器

获取

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
 public function getFirstNameAttribute($value) {
  return ucfirst($value);
 }
}

使用 Laravel 加密器 来加密一个被保存在数据库中的值,当你从 Eloquent 模型访问该属性时该值将被自动解密。

$user = App\User::find(1);
$firstName = $user->first_name;

修改

public function setFirstNameAttribute ($value) {
 $this->attributes['first_name'] = strtolower($value);
}
$user = App\User::find(1);
$user->first_name = 'Sally';

日期转化器

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{
 protected $dates = [
  'created_at',
  'updated_at',
  'deleted_at'
 ];
}
$user = App\User::find(1);
$user->deleted_at = Carbon::now();
$user->save();

可在属性上使用任何 Carbon 方法:

$user = App\User::find(1);
echo $user->deleted_at->getTimestamp();

设置时间格式

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model {
 protected $dateFormat = 'U';
}

属性类型转化

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
 protected $casts = [
  'is_admin' => 'boolean',
 ];
}

现在当你访问 is_admin 属性时,它将会被转换成布尔值,即便保存在数据库里的值是一个整数:

$user = App\User::find(1);
if ($user->is_admin) {
 //
}

支持的转换的类型有:

integer
real
float
double
string
boolean
object
array
collection
date
datetime
timestamp

# protected $casts = [
#  'options' => 'array',
# ];

$user = App\User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();

序列化模型或集合

序列化成数组

$user = App\User::with('roles')->first();
return $user->toArray();

序列化成 JSON

$user = App\User::find(1);
return $user->toJson();
// 或者
return (string) $user; // 自动调用 toJson
// 或者
return App\User::all();
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/4120.html