Laravel日记

1.单行为控制器

//控制器
    public function __invoke(){
     
        //
    }
//路由
Route::get('demo19', 'Test\TestController');  

2.路由回退

//没有找到会运行此路由
//放到最底部
Route::fallback(function () {
     
    return redirect('/');
});

3.路由信息

//当前路由信息
dump(Route::current());
//当前路由的别名
echo Route::currentRouteName();
//当前路由指向的方法
echo Route::currentRouteAction();

4.资源控制器

HTTP请求方式 URL 控制器方法 路由命名 业务逻辑描述
GET post index() post.index 展示所有文章
GET post/create create() post.create 发布文章表单页面(api无)
POST post store() post.store 获取表单提交数据并保存新文章
GET post/{id} show() post.show 展示单个文章
GET post/{id}/edit edit() post.edit 编辑文章表单页面(api无)
PUT post/{id} update() post.update 获取编辑表单输入并更新文章
DELETE post/{id} destroy() post.destroy 删除单个文章
// php artisan make:controller UserController --resource
// php artisan make:controller UserController --api

//单个资源路由
Route::resource('api', 'Test\ApiController');
//api资源路由
Route::apiResource('api', 'Test\ApiController');

//批量资源路由
Route::resources([
    'api'=>'Test\ApiController'
]);

5.数据库分块操作

//再有一万条数据的时候 每次取出100条操作
//where条件下的update会有坑
$result = DB::table('uinfo')
            ->orderBy('id')
            ->chunk(100, function ($result) {
     
                foreach ($result as $item) {
     
                    $item->username = $item->username . '###22';
                }
            });

6.数据库判断数据是否存在

//返回 true
DB::table('uinfo')->where('id', 19)->exists();
//返回 false
DB::table('uinfo')->where('id', 19)->doesntExist()

7.数据库select查询

//1.addSelect
//给已经构建好的查询添加更多字段
 $base = DB::table('uinfo')->select('username', 'password');
        $result = $base->addSelect('updated_at')->get();
//2.DB::raw()
//select()内部实现原生表达式
$result = DB::table('uinfo')->select(DB::raw('count(*) as num'))
            ->groupBy('username')
            ->get();  
//3.selectRaw
//selectRaw()内部实现原生表达式
$result=DB::table('uinfo')
            ->groupBy('username')
            ->selectRaw('count(*) as num,username')
            ->get();                

8.updateOrInsert 存在修改,不存在新增

 $result = DB::table('uinfo')->updateOrInsert(
            ['id' => 15],
            ['username' => 'demo14的测试1', 'password' => '123456', 'updated_at' => $time, 'created_at' => $time]
        );

9.Laravel增加代码提示

composer require barryvdh/laravel-ide-helper
php artisan ide-helper:generate – 为Facades 生成注释
php artisan ide-helper:models – 为数据模型生成注释
php artisan ide-helper:meta – 生成PhpStorm Meta file

10.模型作用域:本地作用域

//模型中 前面需要使用scope
public function scopeCheckId($query, $index)
{
     
    return $query->where('id', '>', $index);
}
//控制器
$result = Uinfo::checkId(5)->get();

11.模型作用域:全局作用域

//创建类
namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class NameScope implements Scope
{
     
    public function apply(Builder $builder, Model $model)
    {
     
        // TODO: Implement apply() method.

        return $builder->where('id', '>', 6);
    }
}

//2.开启全局作用域
protected static function boot()
{
     
    parent::boot(); // TODO: Change the autogenerated stub
    static::addGlobalScope(new NameScope());
}

12.模型访问器

//访问器 前:get 中:字段名 后:Attribute
public function getUsernameAttribute($value)
{
     
     return '[' . $value . ']';
}
//虚拟字段
protected $appends = ['info'];
public function getInfoAttribute()
{
     
     return '##'.$this->password;
}

13.模型修改器

public function setPasswordAttribute($value)
{
     
    $this->attributes['password'] = '&&' . $value;
}

14.模型预加载 with

//Ucard模型
public function be_user()
{
     
    return $this->belongsTo(Uinfo::class, 'u_id', 'id');
}
//控制器
$result = Ucard::with('be_user')->get();

$result = Ucard::with(['be_user' => function ($query) {
     
    $query->where('id', '>', 5);
}])->get();

15.模型关联(一对多)增删改

//Uinfo模型
public function userCard()
{
     
    return $this->Hasone(Ucard::class, 'u_id', 'id');
}
//控制器
//save
$result = Uinfo::find(15)->userCard()->save(new Ucard(['card' => '15646484']));
//create
Uinfo::find(15)->userCard()->create(['card' => 2525]);
//update
Uinfo::find(15)->userCard()->update(['card' => '修改']);
//delete
Uinfo::find(9)->userCard()->delete();

16.模型关联(多对多)增删改

//Article模型
public function rel_article()
{
     
    return $this->belongsToMany(Keyword::class, 'a_k', 'a_id', 'k_id');
}
//控制器
$k_id = 6;
//attach 增加 a_id=1,k_id=6
Article::find(1)->rel_article()->attach($k_id, ['remarks' => '多对多增加']);
//sync 唯一新增 不存在新增(会删除之前)
Article::find(1)->rel_article()->sync($k_id);
//detach 删除 a_id=1,k_id=6
Article::find(1)->rel_article()->detach($k_id);
//updateExistingPivot 修改
Article::find(1)->rel_article()->updateExistingPivot(3, ['remarks' => '修改']);

你可能感兴趣的:(Laravel,php,laravel)