初次使用clone,是因为使用了Laravel的dbBuilder

感觉还行。刚才程序一直报bug。结果查到是因为

DB::table('article')

分别被用于get()和count()。

想起重新写一遍构造方法太麻烦,于是想到了php自带的clone函数。Bug消除了!


<?php

class ArticlesController extends BaseController
{
	public function get()
	{
		$limit = Input::get('limit') ? : 5;
		$offset = Input::get('offset') ? : 0;
		$keyword_all = Input::get('keyword');	//关键字以$$号分割
		$keywords = explode('$$', $keyword_all);
		
		$articleSqlHandler = DB::table('article')->select('id', 'title', 'createtime');
		
		//FIXME:关键字太多,会引起慢查询
		if($keywords):
			foreach($keywords as $keyword):
				$articleSqlHandler->where('content', 'like', "%$keyword%");
			endforeach;
		endif;
		
		$toCountHander = clone $articleSqlHandler;
		$articleInfo = $articleSqlHandler->skip($offset)->take($limit)->get();
		
		$addition = [
			'total' => $toCountHander->count(),
		];
		
		echo Restapi::success($articleInfo, $addition);
	}

	public function post()
	{
		
	}

	public function put()
	{
		
	}

	public function delete()
	{
		
	}
}

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