Laravel日记

此文转载自:https://blog.csdn.net/qq_43489208/article/details/112471834#commentBox

1.单行为控制器

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

2.路由回退

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

3.路由信息

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

4.资源控制器

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

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

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

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 AppScopes;

use IlluminateDatabaseEloquentBuilder;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentScope;

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' => '修改']);
   

更多内容详见微信公众号:Python测试和开发

Python测试和开发

原文地址:https://www.cnblogs.com/phyger/p/14277467.html