Laravel 查询在 DB::Table 和 DB::Select 中使用内连接显示不同的结果
Laravel query showing different Result in DB::Table and DB::Select with inner join
我正在使用 3 table
1.organizations
2.users
3.organization_user
所以 organization_user 是获取 org 的枢轴 table。和用户。
DB::select("SELECT users.name 'User Name',organizations.name 'Org Name'
FROM users INNER JOIN organization_users ON
organization_users.user_id=users.id
INNER JOIN organizations ON
organizations.id=organization_users.organization_id
WHERE organization_users.organization_id=$org_id");
得到以下结果
[
{
"User Name": "Navid Anjum",
"Org Name": "org1"
},
{
"User Name": "kamal",
"Org Name": "org1"
} ]
但是当使用
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.id','=',$org_id)
->get();
得到以下结果
[
{
"Name": "Navid Anjum",
"Org Name": "org1"
} ]
所以我做错了什么?
您在第二个语句中没有为 organization_users 设置正确的 ID :
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.organization_id','=',$org_id)
->get();
我正在使用 3 table 1.organizations 2.users 3.organization_user
所以 organization_user 是获取 org 的枢轴 table。和用户。
DB::select("SELECT users.name 'User Name',organizations.name 'Org Name'
FROM users INNER JOIN organization_users ON
organization_users.user_id=users.id
INNER JOIN organizations ON
organizations.id=organization_users.organization_id
WHERE organization_users.organization_id=$org_id");
得到以下结果
[ { "User Name": "Navid Anjum", "Org Name": "org1" }, { "User Name": "kamal", "Org Name": "org1" } ]
但是当使用
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.id','=',$org_id)
->get();
得到以下结果
[ { "Name": "Navid Anjum", "Org Name": "org1" } ]
所以我做错了什么?
您在第二个语句中没有为 organization_users 设置正确的 ID :
DB::table('organization_users')
->join('users','users.id','=','organization_users.user_id')
->join('organizations','organizations.id','=',
'organization_users.organization_id')
->select('users.name as Name','organizations.name as Org Name')
->where('organization_users.organization_id','=',$org_id)
->get();