Laravel Eloquent 日期系列化

Laravel Eloquent 日期系列化成 json,默认系列化格式为:2023-03-08T08:16:02.000000Z
原因是 Laravel 模型基类的 serializeDate() 时间系列化方法调用 Carbon\Traits\Converter::toJSON() 方法,返回的是 ISO-8601 格式的日期。

引起问题的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Illuminate\Database\Eloquent\Concerns\HasAttributes
protected function serializeDate(DateTimeInterface $date)
{
return $date instanceof DateTimeImmutable ?
CarbonImmutable::instance($date)->toJSON() :
Carbon::instance($date)->toJSON();
}

// class Carbon\Traits\Converter
public function toJSON()
{
return $this->toISOString();
}
阅读更多

Laravel Eloquent 模型属性参数详解

@TODO

$table

模型绑定表名,默认是模型类名 kebab-case 带下划线小写的复数形式。

$primaryKey = ‘id’

$keyType = ‘integer’

fillable

attributes

hidden

casts

数字、字符串类型不需要转换。

appends

$timestamps = true

$dateFormat = ‘Y-m-d H:i:s’

Laravel Eloquent 数据库关联模型的增删改操作

Laravel Eloquent ORM 提供了数据模型关联表操作的 API,熟练掌握这些API后,才体会到 Laravel 数据库操作有多高效。

一、hasMany 一对多关联

save/saveMany 创建关联记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 新建一条数据 Post 的评论,save 将自动添加 post_id 字段
$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$post->comments()->save($comment);

// 保持多条记录
$post->comments()->saveMany([
new Comment(['message' => 'A new comment.']),
new Comment(['message' => 'Another new comment.']),
]);

// 更新后需要重新加载模型及其关联,才会加到 $post->comments 中
$post->refresh();

// 所有评论,包括新保存的评论...
$post->comments;

create/createMany 创建关联记录

save/saveMany 的区别是参数时数组,而不是模型。

阅读更多

Laravel Eloquent 数据库关联查询

Eloquent

子查询

1
2
3
4
5
6
7
User::query()->whereIn(
'id',
UserRolePivot::query()
->select('user_id')
->where('role_id', $roleId)
)->get();
// SELECT * FROM user WHERE id IN( SELECT user_id FROM user_role_pivot WHERE role_id = $roleId)

分组查询

阅读更多