视图查询-j9九游
视图查询可以实现不依赖数据库视图的多表查询,并不需要数据库支持视图,例如:
db::view('user','id,name')
->view('profile','truename,phone,email','profile.user_id=user.id')
->view('score','score','score.user_id=profile.id')
->where('score','>',80)
->select();
生成的sql语句类似于:
select user.id,user.name,profile.truename,profile.phone,profile.email,score.score from think_user user inner join think_profile profile on profile.user_id=user.id inner join think_socre score on score.user_id=profile.id where score.score > 80
注意,视图查询无需调用
table
和join
方法,并且在调用where
和order
方法的时候只需要使用字段名而不需要加表名。
默认使用inner join查询,如果需要更改,可以使用:
db::view('user','id,name')
->view('profile','truename,phone,email','profile.user_id=user.id','left')
->view('score','score','score.user_id=profile.id','right')
->where('score','>',80)
->select();
生成的sql语句类似于:
select user.id,user.name,profile.truename,profile.phone,profile.email,score.score from think_user user left join think_profile profile on profile.user_id=user.id right join think_socre score on score.user_id=profile.id where score.score > 80
可以使用别名:
db::view('user',['id'=>'uid','name'=>'account'])
->view('profile','truename,phone,email','profile.user_id=user.id')
->view('score','score','score.user_id=profile.id')
->where('score','>',80)
->select();
生成的sql语句变成:
select user.id as uid,user.name as account,profile.truename,profile.phone,profile.email,score.score from think_user user inner join think_profile profile on profile.user_id=user.id inner join think_socre score on score.user_id=profile.id where score.score > 80
可以使用数组的方式定义表名以及别名,例如:
db::view(['think_user'=>'member'],['id'=>'uid','name'=>'account'])
->view('profile','truename,phone,email','profile.user_id=member.id')
->view('score','score','score.user_id=profile.id')
->where('score','>',80)
->select();
生成的sql语句变成:
select member.id as uid,member.name as account,profile.truename,profile.phone,profile.email,score.score from think
文档最后更新时间:2018-04-26 09:52:31
未解决你的问题?请到「问答社区」反馈你遇到的问题