数据库、ORM 以及关系等常用操作

老牛浏览 34评论 0发表于 更新于

数据库

1. 查询

多个

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

单个

php
// 按条件查询单个
$user = DB::table('users')->where('name', 'John')->first();
// 查询不到抛异常
$user = DB::table('users')->where('name', 'John')->firstOrFail();
// 查询单条记录并返回 email 字段值
$email = DB::table('users')->where('name', 'John')->value('email');
// 按 ID 查询
$user = DB::table('users')->find(3);

字段

php
// 获取表中所有 title 字段值
$titles = DB::table('users')->pluck('title');

// 获取表中所有 title 字段值,并以 name 字段值为键
$titles = DB::table('users')->pluck('title', 'name');

是否存在

php
// 存在
DB::table('orders')->where('finalized', 1)->exists();

// 不存在
DB::table('orders')->where('finalized', 1)->doesntExist();

2. 插入

单个

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

多个

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

3. 更新

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

更新或插入

php
DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

增加和减少

php
// votes +1
DB::table('users')->increment('votes');
// votes +5
DB::table('users')->increment('votes', 5);

// votes -1 
DB::table('users')->decrement('votes');
// votes -5
DB::table('users')->decrement('votes', 5);

// votes +1, 并更新其他字段值
DB::table('users')->increment('votes', 1, ['name' => 'John']);

4. 删除

php
// 删除所有记录
$deleted = DB::table('users')->delete();

// 删除符合条件的记录
$deleted = DB::table('users')->where('votes', '>', 100)->delete();

ORM

1. 查询单个模型

php
// 按条件查询
$flight = Flight::where('active', 1)->first();

// 按 ID 查询
$flight = Flight::find(1);

还可以使用 firstOrFailfindOrFail()

查询或创建

php
// 按 name 查询,或不存在时创建
$flight = Flight::firstOrCreate([
    'name' => 'London to Paris'
]);
// 按 name 查询,或使用合并后的数组新建
$flight = Flight::firstOrCreate(
    ['name' => 'London to Paris'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

// 和上面区别在于只会创建实例,并不会持久化到数据库
$flight = Flight::firstOrNew([
    'name' => 'London to Paris'
]);

$flight = Flight::firstOrNew(
    ['name' => 'Tokyo to Sydney'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

2. 插入

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

$flight = Flight::create([
    'name' => 'London to Paris',
]);

3. 更新

php
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();

$flight->update([
	'name' => 'Paris to London'
]);

更新或创建

php
$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

4. 删除

php
// 通过模型实例删除
$flight = Flight::find(1);
$flight->delete();

// 通过 ID 删除
Flight::destroy(1);

Flight::destroy(1, 2, 3);

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

// 通过查询构造器按条件删除
$deleted = Flight::where('active', 0)->delete();
// 删除全部
$deleted = Flight::query()->delete();

ORM 关系

save

通过模型关系可以很方便的新增模型:

php
// 新增单个
$comment = new Comment(['message' => '一条新评论。']);
$post = Post::find(1);
$post->comments()->save($comment);

// 新增多个
$post = Post::find(1);
$post->comments()->saveMany([
    new Comment(['message' => '一条新评论。']),
    new Comment(['message' => '另一条新评论。']),
]);

save 后不会将新增的模型添加到父模型的关系上,可以使用 refresh 重新加载模型及关系来访问。

create

除了 savesaveMany 方法,还可以通过 create,使用属性值来创建模型:

php
$post = Post::find(1);
$comment = $post->comments()->create([
    'message' => '一条新评论。',
]);

$post = Post::find(1);
$post->comments()->createMany([
    ['message' => '一条新评论。'],
    ['message' => '另一条新评论。'],
]);

其他方法还有 createQuietly, createManyQuietly, findOrNew, firstOrNew, firstOrCreate, updateOrCreate

Belongs To 关系

可以通过 associate 将子模型分配给父模型:

php
// 在子模型上设置外键
$account = Account::find(10);
$user->account()->associate($account);
$user->save();

// 在子模型上设置外键为 null
$user->account()->dissociate();
$user->save();

多对多关系

附加或分离
php
// 附加
$user = User::find(1);
$user->roles()->attach($roleId);
// 附加并更新中间表属性
$user->roles()->attach($roleId, ['expires' => $expires]);
// 附加指定 ID 并更新中间表属性
$user->roles()->attach([
    1 => ['expires' => $expires],
    2 => ['expires' => $expires],
]);

// 分离
$user->roles()->detach($roleId);
// 分离所有
$user->roles()->detach();
// 分离指定 ID
$user->roles()->detach([1, 2, 3]);
同步
php
// 指定要保留的 ID
$user->roles()->sync([1, 2, 3]);
// 指定要保留的 ID 以及要保存到中间表的属性
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
// 指定要保留的 ID 以及批量指定要保存到中间表的属性
$user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]);
// 指定要保留的 ID,同时不删除已有的
$user->roles()->syncWithoutDetaching([1, 2, 3]);
切换

如果当前已附加则分离,已分离则附加:

php
$user->roles()->toggle([1, 2, 3]);
$user->roles()->toggle([
    1 => ['expires' => true],
    2 => ['expires' => true],
]);
点赞
收藏
暂无评论,快来发表评论吧~
私信
老牛,俗称哞哞。单纯的九零后理工小青年。喜欢折腾,爱玩,爱音乐,爱游戏,爱电影,爱旅游...
最后活跃于