Eyoucms程序开发:视图查询

站长学院 0次 来源:天荣CMS 收藏

视图查询可以实现不依赖数据库视图的多表查询,并不需要数据库支持视图,例如:

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

免责声明:1.凡本站注明“来源:XXX(非天荣模板网)”的作品,均转载自其它媒体,所载的文章、图片、音频视频文件等资料的版权归版权所有人所有,如有侵权,请联系tianrongcms#foxmail.com处理;2.凡本站转载内容仅代表作者本人观点,与天荣模板网无关。凡本站转载内容仅代表作者本人观点,与本站无关。

凡本站转载内容仅代表作者本人观点,与本站无关。

相关文档

0 条评论

网友留言

免责声明:1.凡本站注明"来源:XXX(非本站)"的作品,均转载自其它媒体,所载的文章、图片、音频视频文件等资料的版权归版权所有人所有,如有来源标注错误或侵犯了您的合法权益,请联系本站处理;2.本站部分内容转载自老K模板网(www.laokcms.com),转载内容仅代表作者本人观点,与本站无关。