Thinkphp提供数据库连贯操作的组件,方便在进行增删改查时更清晰流畅。
查询条件 WHERE
通过 where() 方法可以对sql语句添加where条件
public function index(){
$user = M("user");
if(IS_GET){
/*这段是不使用where方法的
$username = I("username");
$where = "username = '$username'";
$data = $user->where($where)->select();
*/
$map = I();
$map = array_filter($map); //过滤值为空的数组
$map['username'] = array('LIKE',"%{$map['username']}%"); //模糊匹配
$data = $user->where($map)->select();
}else{
$data = $user->select();
}
$this->assign("users",$data);
$this->display();
}
查询字段 field
通过 field() 方法可以对select查找的字段进行限制,同时也能对增加和修改数据时限制字段。
public function index(){
$user = M("user");
if(IS_GET){
$map = I();
$map = array_filter($map); //过滤值为空的数组
$map['username'] = array('LIKE',"%{$map['username']}%"); //模糊匹配
$data = $user->where($map)->field("id,username,password,email")->select();
//$data = $user->where($map)->field("id",true)->select(); //field方法设置true可以选择除了 id 以外的其他字段
}
$this->assign("users",$data);
$this->display();
}
排序 order
通过 order() 方法可以对查询结果进行排序
public function index(){
$user = M("user");
if(IS_GET){
$map = I();
$map = array_filter($map); //过滤值为空的数组
$map['username'] = array('LIKE',"%{$map['username']}%"); //模糊匹配
$data = $user->where($map)->order("id DESC")->field("id,username,password,email")->select();
}
$this->assign("users",$data);
$this->display();
}
多表查询 table
多表查询,可以使用 table() 方法
public function index(){
$model = M();
$data = $model->field("article.*,user.username")->table("tp_user user,cms_article article")->where("user.id=article.userId")->select();
dump($data);
}
注意:使用 table 多表查询时表名要带上前缀,同时where条件至少有表的个数减一个
表关联 join
使用join()可以对两张表进行关联,LEFT JOIN 或 RIGHT JOIN
public function index(){
$article = M("article");
//$data = $article->join("tp_user ON tp_user.id = tp_article.userId")->field("tp_article.*,tp_user.username")->select();
$data = $article->join("LEFT JOIN tp_user ON tp_user.id = tp_article.userId")->field("tp_article.*,tp_user.username")->select();
dump($data);
}
