laravel知识总结

laravel 安装

  • composer 安装laravel安装器
  • laravel new laravel_name

artisan命令

  • 创建控制器

php artisan make:controller UserController
php artisan make:controller Admin/UserController

  • 创建model

php artisan make:model MyTest

  • 创建迁移

php artisan migrate

  • 回滚迁移

php artisan migrate:rollback

  • 回滚所有迁移

php artisan migrate:refresh

  • 数据填充

  • 数据填充插入

  • 事件

php artisan event:generate

  • 路由

php artisan route:list

  • 路由缓存

php artisan route:cache

队列

  • 队列配置文件存储在 config/queue.php
  • 队列的任务类都默认放在 app/Jobs 目录下

php artisan make:job ProcessPodcast

MD5FileJob::dispatch()->onQueue(‘md5’);

// 这个任务将会被分发到默认队列…
Job::dispatch();

//这个任务将会被分发到「emails」队列…
Job::dispatch()->onQueue(‘emails’);

错误

  • http异常:辅助函数:abort 辅助函数;
  • try{ } catch (Exception $e) {}

日志

  • laravel 的日志系统基于 Monolog
  • 日志等级:emergency、 alert、critical、 error、 warning、 notice、 info 和 debug。

Log::debug(‘An informational message.’);

Log::emergency($message);

Log::alert($message);

Log::critical($message);

Log::error($message);

Log::warning($message);

Log::notice($message);

Log::info($message);

Log::debug($message);

  • 记录日志到指定通道

有时候你可能希望将日志记录到指定通道。你可以使用 Log Facade 中的 channel 方法,将日志记录到应用配置中存在的任何渠道:

Log::channel(‘slack’)->info(‘Something happened!’);
Log::channel(‘upload’)->error(‘ueditor error’, [‘e’=>$e]);

如果你想按需创建多个渠道的日志堆栈,你可以使用 stack 方法:

Log::stack([‘single’, ‘slack’])->info(‘Something happened!’);

邮件发送

事件和监听

目的:解耦

用法:
1 在providers目录中,修改EventServiceProvides.php
2 php artisan event:generate进行生成event和listener
3 在listener中写功能逻辑

数据库

  • 简介

Laravel 能使用原生 SQL、查询构造器 和 Eloquent ORM 在各种数据库后台与数据库进行非常简单的交互

  • 查询构造器
  • ---------------- 查询 ----------------

DB::table(‘users’)->get();
get、first、value

  • 获取一列的值

DB::table(‘roles’)->pluck(‘title’);

  • 获取结果集

keyBy(‘day’) 将结果集,以day值为键名,进行获取结果集
keys() 返回集合的所有键。

  • 分块结果 chunk()

  • 聚合函数:count() max() avg()

  • 确定记录是否存在

return DB::table(‘orders’)->where(‘finalized’, 1)->exists();
return DB::table(‘orders’)->where(‘finalized’, 1)->doesntExist();

  • select语句

DB::table(‘users’)->select(‘name’, ‘email as user_email’)->get();

  • distinct 允许你强制让查询返回不重复的结果:

$users = DB::table(‘users’)->distinct()->get();

  • 原生表达式 DB::raw

$users = DB::table(‘users’)
->select(DB::raw(‘count(*) as user_count, status’))
->where(‘status’, ‘<>’, 1)
->groupBy(‘status’)
->get();

  • 原生方法

selectRaw 方法可以用来代替 select(DB::raw(…))。这个方法的第二个参数接受一个可选的绑定参数数组:
$orders = DB::table(‘orders’)
->selectRaw(‘price * ? as price_with_tax’, [1.0825])
->get();

  • whereRaw / orWhereRaw

可以使用 whereRaw 和 orWhereRaw 方法将原生的 where 注入到你的查询中。这些方法接受一个可选的绑定数组作为他们的第二个参数:

$orders = DB::table(‘orders’)
->whereRaw(‘price > IF(state = “TX”, ?, 100)’, [200])
->get();

  • havingRaw / orHavingRaw

havingRaw 和 orHavingRaw 方法可用于将原生字符串设置为 having 语句的值:

$orders = DB::table(‘orders’)
->select(‘department’, DB::raw(‘SUM(price) as total_sales’))
->groupBy(‘department’)
->havingRaw(‘SUM(price) > 2500’)
->get();

  • orderByRaw 可用于将原生字符串设置为 order by 子句的值

$orders = DB::table(‘orders’)
->orderByRaw(‘updated_at - created_at DESC’)
->get();

  • Where 语句

orWhere(‘name’, ‘John’)

  • whereBetween 方法验证字段的值位于两个值之间:

$users = DB::table(‘users’)
->whereBetween(‘votes’, [1, 100])->get();

  • whereNotBetween 方法验证字段的值位于两个值之外

$users = DB::table(‘users’)
->whereNotBetween(‘votes’, [1, 100])
->get();

  • whereIn方法验证字段的值在指定的数组内:

$users = DB::table(‘users’)
->whereIn(‘id’, [1, 2, 3])
->get();

  • whereHas方法验证字段的值在指定的数组内:

$query->whereHas(‘items’, function ($query) use ($aid) {
return $query->where(‘aid’, $aid);
});

  • doesntHave(‘orderRefund’)

  • whereNotIn 方法验证字段的值 不 在指定的数组内:

$users = DB::table(‘users’)
->whereNotIn(‘id’, [1, 2, 3])
->get();

  • whereNull 方法验证字段的值为 NULL:

$users = DB::table(‘users’)
->whereNull(‘updated_at’)
->get();

  • whereNotNull 方法验证字段的值不为 NULL:

$users = DB::table(‘users’)
->whereNotNull(‘updated_at’)
->get();

  • whereDate 方法用于比较字段的值和日期:

$users = DB::table(‘users’)
->whereDate(‘created_at’, ‘2016-12-31’)
->get();

  • whereMonth 方法用于比较字段的值与一年的特定月份:

$users = DB::table(‘users’)
->whereMonth(‘created_at’, ‘12’)
->get();

  • whereDay 方法用于比较字段的值与一个月的特定日期:

$users = DB::table(‘users’)
->whereDay(‘created_at’, ‘31’)
->get();

  • whereYear 方法用于比较字段的值与特定年份:

$users = DB::table(‘users’)
->whereYear(‘created_at’, ‘2016’)
->get();

  • whereTime 用于将字段的值与特定的时间进行比较:

$users = DB::table(‘users’)
->whereTime(‘created_at’, ‘=’, ‘11:20’)
->get();

  • whereColumn 方法用于验证两个字段是否相等:

$users = DB::table(‘users’)
->whereColumn(‘first_name’, ‘last_name’)
->get();

还可以将比较运算符传递给该方法:
$users = DB::table(‘users’)
->whereColumn(‘updated_at’, ‘>’, ‘created_at’)
->get();

还可以传递多条件数组到 whereColumn 方法,这些条件通过 and 运算符连接:
$users = DB::table(‘users’)
->whereColumn([
[‘first_name’, ‘=’, ‘last_name’],
[‘updated_at’, ‘>’, ‘created_at’]
])->get();

  • 条件语句

有时你可能想要子句只适用于某个情况为真时才执行查询。例如,你可能只想给定值在请求中存在的情况下才应用 where 语句。你可以通过使用 when 方法:

$role = $request->input(‘role’);
u s e r s = D B : : t a b l e ( ′ u s e r s ′ ) − > w h e n ( users = DB::table('users') ->when( users=DB::table(users)>when(role, function ( q u e r y ) u s e ( query) use ( query)use(role) {
return $query->where(‘role_id’, $role);
})
->get();

  • inRandomOrder 方法可以将查询结果随机排序。例如, 你可以使用这个方法获取一个随机用户

$randomUser = DB::table(‘users’)
->inRandomOrder()
->first();

  • 插入

DB::table(‘users’)->insert([
[‘email’ => ‘taylor@example.com’, ‘votes’ => 0],
[‘email’ => ‘dayle@example.com’, ‘votes’ => 0]
]);

  • 自增 ID

$id = DB::table(‘users’)->insertGetId(
[‘email’ => ‘john@example.com’, ‘votes’ => 0]
);

  • 自增自减

DB::table(‘users’)->increment(‘votes’, 5);
DB::table(‘users’)->decrement(‘votes’);

  • 更新

DB::table(‘users’)
->where(‘id’, 1)
->update([‘votes’ => 1]);

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

  • 删除

DB::table(‘users’)->where(‘votes’, ‘>’, 100)->delete();
DB::table(‘users’)->truncate();

  • 悲观锁

查询构造器也包含一些可以帮助你在 select 语法上实现 「悲观锁定」的函数。若想在查询中实现一个「共享锁」,你可以使用 sharedLock 方法。共享锁可防止选中的数据列被篡改,直到事务被提交为止 :

DB::table(‘users’)->where(‘votes’, ‘>’, 100)->sharedLock()->get();

另外,你也可以使用 lockForUpdate 方法。使用「更新」锁可避免行被其它共享锁修改或选取:

DB::table(‘users’)->where(‘votes’, ‘>’, 100)->lockForUpdate()->get();

Eloquent ORM

  • 简介

Laravel 的 Eloquent ORM 提供了漂亮、简洁的 ActiveRecord 实现来和数据库交互。每个数据库表都有一个对应的「模型」用来与该表交互。你可以通过模型查询数据表中的数据,并将新记录添加到数据表中。

  • ---------------- 查询 ----------------
  • 获取模型

Model::all() 获取所有数据
Model::where()->orderBy()->take(10)->get();

  • 分块结果

chunk 方法可节省内存
Model::chunk(200,function($flights){});

  • 使用游标

foreach (Flight::where(‘foo’, ‘bar’)->cursor() as $flight) {}

  • 检索单个模型/集合

Model::find() 主键取回一个模型
Model::find([1,2,3]);
Model::where()->first(); 取回符合查询限制的第一个模型…
Model::findOrFail(1); 在找不到模型时抛出异常
Model::where()->firstOrFail();

  • 检索集合

count、sum、max
Model::where(‘active’, 1)->count();
Model::where(‘active’, 1)->max(‘price’);

  • ----------------插入 & 更新模型 ----------------
  • 插入和更新

Object->save();

  • 批量更新

Model::where(‘active’, 1) ->where(‘destination’, ‘San Diego’) ->update([‘delayed’ => 1]);

  • 批量赋值

Model::create([‘name’ => ‘Flight 10’]);
firstOrCreate
updateOrCreate

  • ---------------- 删除模型 ----------------
  • 删除模型

Model::find(1);
$flight->delete();

Model::destroy(1);

Model::where(‘active’, 0)->delete();

  • 软删除

deleted_at protected $dates = [‘deleted_at’];

  • withTrashed 方法获取包括软删除在内的模型

Model::withTrashed()->where(‘account_id’, 1)->get();

  • onlyTrashed 检索软删除模型

$flights = Model::onlyTrashed()->where(‘airline_id’, 1)->get();

  • 恢复软删除模型

$flight->restore();

  • forceDelete 永久删除

// 单个模型实例的永久删除
$flight->forceDelete();

// 关联模型的永久删除
$flight->history()->forceDelete();

  • scope 本地范围

你可能经常需要获取「受欢迎的」用户。要定义这样一个范围,只需要在对应的 Eloquent 模型方法前加入 scope 前缀
public function scopeActive($query)
{
return $query->where(‘active’, 1);
}

利用本地范围
一旦定义范围。就可以在模型查询的时候调用范围方法。在方法调用时你不需要添加 scope 前缀。你甚至可以链式调用不同的范围,例如:
$users = Model::popular()->active()->orderBy(‘created_at’)->get();

  • 模型关联
  • 一对一

return $this->hasOne(‘App\Phone’);
$phone = User::find(1)->phone;

belongsTo 方法来定义反向关联

  • 一对多

return $this->hasMany(‘App\Comment’);
$comments = App\Post::find(1)->comments;

$comments = App\Post::find(1)->comments()->where(‘title’, ‘foo’)->first();

  • 一对多(反向)

belongsTo 方法定义它

  • 多对多关联通过写方法定义,在这个方法的内部调用 belongsToMany 方法并返回其结果

$roles = App\User::find(1)->roles()->orderBy(‘name’)->get();

  • 定义反向关联

调用 belongsToMany 方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阳光帅气男孩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值