版权声明:本文为ywcmoon原创文章,未经允许不得转载。 https://blog.csdn.net/qq_39251267/article/details/82257604
视图查询可以实现不依赖数据库视图的多表查询,并不需要数据库支持视图,例如:
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_user member
INNER JOIN think_profile PROFILE ON PROFILE .user_id = member.id
INNER JOIN think_socre Score ON Score.user_id = PROFILE .id
WHERE
Score.score > 80