laravel使用过程中一些总结

推荐连接:
laravel辅助函数总结:https://laravel-china.org/docs/laravel/5.5/helpers
基于 Laravel 集成的 Monolog 库对日志进行配置和记录  http://laravelacademy.org/post/1878.html
laravel中缓存的使用 https://blog.csdn.net/huang2017/article/details/70228473
laravel原理机制分析 https://www.cnblogs.com/XiongMaoMengNan/p/6644892.html
laravel原理分析专栏 https://laravel-china.org/laravel-source
laravel服务容器实现原理 https://segmentfault.com/a/1190000008892574
laravel中间件原理 https://segmentfault.com/a/1190000009988874
laravel facade实现原理 https://blog.csdn.net/hizzana/article/details/53212323

Request中的操作:
获取用户提交的值:Input::get('name');
获取用户提交的值并指定默认值:Input::get('name', 'Sally');
用户提交的信息是否存在:Input::has('name')
获取所有用户提交的信息:Input::all()
获取其中几项指定的信息:Input::only('username', 'password');
获取除几项之外的提交信息:Input::except('card');
访问用户提交的数组:Input::get('products.0.name');
cookie操作:
获取Cookie中的值:Cookie::get('name')
添加一个Cookie:
$response = Response::make('Hello World');
response−>withCookie(Cookie::make(′name′,′value′,response−>withCookie(Cookie::make(′name′,′value′,minutes));
如果想在Response之前设置Cookie,使用Cookie::queue()
Cookie::queue(name,name,value, $minute);
Session操作:
存储一个变量:Session::put('key', 'value');
读取一个变量:Session::get('key');
读取一个变量或者返回默认值:Session::get('key', 'default');
检查一个变量是否存在:Sesssion::has('key');
删除一个变量:Session::forget('key');
删除所有Session变量:Session::flush();
文件上传操作:
获取用户上传文件:$file = Input::file('photo');
判断是否有上传这个文件:Input::hasFile('photo');
移动上传的文件:
Input::file('photo')->move($destinationPath);
Input::file('photo')->move(destinationPath,destinationPath,fileName);
获取上传文件大小:
Input::file('photo')->getSize();
获取上传文件类型:
Input::file('photo')->getMimeType();
获取用户请求路径:Request::path();
获取用户请求URL:Request::url();
获取Header中的信息:Request::header('Content-Type');
获取SERVER中的信息:Request::server('PATH_INFO');
重定向:
重定向: return Redirect::to('user/login');
有参数的重定向: return Redirect::to('user/login')->with('message', 'Login Failed');
重定向到路由:return Redirect::route('profile', array('user' => 1));
返回重定向到Action:return Redirect::action('UserController@profile', array('user' => 1));
视图层:
传递数据给视图:$view = View::make('greeting')->with('name', 'Steve');
将一个视图传递给另一个视图:$view = View::make('greeting')->nest('child', 'child.view');
返回json:return Response::json(array('name' => 'Steve', 'state' => 'CA'));
返回jsonp:return Response::json(array('name' => 'Steve', 'state' => 'CA'))->setCallback(Input::get('callback'));
返回下载文件:
return Response::download($pathToFile);
return Response::download(pathToFile,pathToFile,status, $headers);

// 多where条件查询  
Student::scopeMultiwhere([‘female’=>1, ’teacher_id’ => 4, ‘class_id’ => 3])->get();
    public function scopeMultiwhere($query, $arr)
    {
        if (!is_array($arr)) {
            return $query;
        }
 
        foreach ($arr as $key => $value) {
            $query = $query->where($key, $value);
        }
        return $query;
    }

 
public function rules()
{
    return [
        'location_num' => [
            'required',
            'integer',
            'numeric',
            //'regex:/^([1-9]|^[1][0-9]{1}$|20)$/'//1-20的正整数
            'regex:/^([1-9])$/'//1-9的正整数
        ],
        'award_code' => 'required|string',
        'award_probability' => [
            'required',
            'integer',
            'numeric',
            'regex:/^(0|[1-9]\d?|100)$/'//0-100的正整数
        ],
    ];
}

 
$goodsShow = Goods::where('cate_id','=',$cate_id)
    ->where(function($query){
        $query->where('status','<','61')
            ->orWhere(function($query){
                $query->where('status', '91');
            });
    })->first();
这一段其实执行的就是where cate_id = $cate_id AND (status < 61 OR status = 91)
 
$updateOk = SunBall::query()->where('player_code', $this->playerCode)->where(function ($query) {
                $beginTime = date('Y-m-d H:i:s', time() - 3 * 24 * 3600);
                $query->where('remained_sunbean', '<=', 0)
                    ->orWhere('created_at', '<', $beginTime);
            })->update(['is_available' => 0]);
 
 
DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.id', 'contacts.phone', 'orders.price');
 
 
 
DB::table('users')
            ->whereExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();
 
select * from A where(a=1,b like %123%) or (a=1,b like %456%)
 
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();
 
 
 
A::where(function ($query) {
    $query->where('a', 1)->where('b', 'like', '%123%');
})->orWhere(function ($query) {
    $query->where('a', 1)->where('b', 'like', '%456%');
})->get();
 
 
 
 
DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();
 
DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function($query)
            {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();
 
 
 
$winningInfo = AwardRecord::query()->select(['t_award.award_display_name', 't_award.code', 't_award.display_price'])
    ->leftjoin('t_award', 't_award.code', '=', 't_award_record.award_code')
    ->whereRaw("t_award_record.player_code = (SELECT t_player.`code` FROM t_player WHERE t_player.user_id=$memberId)")
    ->paginate(15);

 
批量添加
$okInverter = \DB::connection('pvm')->table('t_inverter')->insert($invertersInsertData);//$invertersInsertData是二维数组
批量更新
$this->plantDataRep->updateBatch('t_pv_plant_data', $updateData, 'pvm');//$updateData 是二维数组
 
/**
 * @desc 批量更新
 * @createTime 2017-08-24
 * @author yanglibin@sunallies.com
 * @param string $tableName
 * @param array $multipleData
 * @param string $db
 * @return bool|int
 */
public function updateBatch($tableName = "", $multipleData = array(), $db = 'mysql' )
{
    if ($tableName && !empty($multipleData)) {
        // column or fields to update
        $updateColumn = array_keys($multipleData[0]);
        $referenceColumn = $updateColumn[0]; //e.g id
        unset($updateColumn[0]);
        $whereIn = "";
 
        $q = "UPDATE " . $tableName . " SET ";
        foreach ($updateColumn as $uColumn) {
            $q .= $uColumn . " = CASE ";
 
            foreach ($multipleData as $data) {
                $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
            }
            $q .= "ELSE " . $uColumn . " END, ";
        }
        foreach ($multipleData as $data) {
            $whereIn .= "'" . $data[$referenceColumn] . "', ";
        }
        $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";
 
        // Update
        return \DB::connection($db)->update(\DB::connection($db)->raw($q));
 
    } else {
        return false;
    }
 
}

 

 

 

 

 


 
php artisan 的缓存命令如 php artisan config:clear
 
config:clear
debugbar:clear
cache:clear
route:clear
view:clear
config:cache
schedule:run
 

 

 

[program:pvm.center.collectorDeviceSync]
process_name=%(program_name)s_%(process_num)02d
command=php /home/www/sunallies-pvm-center-refactor/artisan queue:work --queue=pvm.center.collectorDeviceSync --sleep=1 --tries=3 --daemon
autostart=true
autorestart=true
user=root
numprocs=2
redirect_stderr=true
stdout_logfile=/home/www/sunallies-pvm-center-refactor/storage/logs/worker.log
 

 
Laravel 服务容器是管理类依赖和运行依赖注入的有力工具。依赖注入是一个花俏的名词,它实质上是指:类的依赖通过构造器或在某些情况下通过「setter」方法进行「注入」
 
 

 
$res = DB::table('topics')->select('topics.*', 'b.username',
            'b.avatar', 'c.username as rname', 'd.cname')
 
            ->where('topics.is_hidden', 0)
 
            ->leftJoin('users AS b', 'b.uid', '=', 'topics.uid')
 
            ->leftJoin('users AS c', 'c.uid', '=', 'topics.ruid')
 
            ->leftJoin('nodes AS d', 'd.node_id', '=', 'topics.node_id')
 
            ->orderBy('ord', 'desc')
 
            ->take($limit)->get();
 

 
将模型转换成数组
$user = User::with('roles')->first();
return $user->toArray();
 
注意:也可以把整个的模型集合转换成数组:
 
return User::all()->toArray();
 
将模型转换成 JSON
 
 
要把模型转换成 JSON,可以使用 toJson 方法:
 
 
return User::find(1)->toJson();
从路由中返回模型

 
//Laravel 5 中需要开启QueryLog
\DB::connection()->enableQueryLog();
//这里为查询操作
print_r(\DB::getQueryLog()); 

 

 

 

 

 

 

posted on 2018-03-23 10:38  Ryanyanglibin  阅读(194)  评论(0编辑  收藏  举报

导航