您好,欢迎访问一九零五行业门户网

thinkphp怎么查询多个数据

thinkphp查询多个数据的方法:1、使用table方法进行多表查询,语法如“$model->table('think_blog blog,think_type type')”;2、使用join方法进行查询,代码如“$model->join('work on artist.id = work.artist_id')”。
本教程操作环境:windows7系统、thinkphp5版、dell g3电脑。
thinkphp怎么查询多个数据?
thinkphp 中关联查询(多表查询)
thinkphp 中关联查询(多表查询)可以使用 table() 方法或和join方法,请看示例:
1、table方法:定义要操作的数据表名称,可以动态改变当前操作的数据表名称,需要写数据表的全名,包含前缀,可以使用别名,例如:
$model->table('think_user user')->where('status>1')->select();$model->table('think_blog blog,think_type type')->where('blog.typeid=type.id')->field('blog.id as id,blog.title,blog.content,type.typename as type')->order('blog.id desc' )->limit(5)->select();
table方法的参数支持字符串和数组,数组方式的用法:
$model->table(array('think_user'=>'user','think_group'=>'group'))->where('status>1')->select();
使用数组方式定义的优势是可以避免因为表名和关键字冲突而出错的情况。
注:如果不定义table方法,默认会自动获取当前模型对应或者定义的数据表。
2、join方法:查询join支持,join方法的参数支持字符串和数组,并且join方法是连贯操作中唯一可以多次调用的方法。例如:
$model->join('work on artist.id = work.artist_id')->join('card on artist.card_id = card.id')->select();//left join$model->table('user u')->join('news n on u.id=n.cid')->field('u.*,n.*')->order('id desc')->limit('8')->findall();
默认采用left join 方式,如果需要用其他的join方式,可以改成
$model->join('right join work on artist.id = work.artist_id')->select();//right join$model->table('user u')->join(array('right','news n on u.id=n.cid'))->field('u.*,n.*')->order('id desc')->limit('8')->findall();
如果join方法的参数用数组的话,只能使用一次join方法,并且不能和字符串方式混合使用。
$model->join(array(' work on artist.id = work.artist_id', 'card on artist.card_id = card.id'))->select()
运用这种连贯操作方法,可以有效的提高数据查询的代码清晰度和开发效率。
查看连贯操作的sql语句的方法:
echo $model->getlastsql(); //打印一下sql语句,查看一下
例2:
1、table()
$list = $user->table('user_status stats, user_profile profile')->where('stats.id = profile.typeid')->field('stats.id as id, stats.display as display, profile.title as title,profile.content as content')->order('stats.id desc' )->select();
2.1、join()2表查询
$user = new model('user');$list = $user->join('right join user_profile on user_stats.id = user_profile.typeid' );
2.2、join() 多表查询
$list = $form->join('think_sort on think_form.sort_id = think_sort.sort_id' )->join('think_brand on think_form.brand_id = think_brand.brand_id' )->select();
3、原生查询
$model = new model();$sql = 'select a.id,a.title,b.content from think_test1 as a, think_test2 as b where a.id=b.id '.$map.' order by a.id '.$sort.' limit '.$p->firstrow.','.$p->listrows;$volist = $model->query($sql);
推荐学习:《thinkphp视频教程》
以上就是thinkphp怎么查询多个数据的详细内容。
其它类似信息

推荐信息