我有三个表:(用户和单词列表之间的多对多关系,userlistrels 是连接器)users:idnamewordlists:idnamecreator_iduserlistrels:iduser_idwordlist_id我想执行以下查询:SELECT * FROM users WHERE id=( SELECT wordlists.creator_id FROM userlistrels JOIN wordlists ON wordlists.id=userlistrels.wordlist_id WHERE userlistrels.user_id=$curr_user )如何WHERE foo= ( subquery )在 Laravel 接口中编写这种类型的子查询()?文档涵盖SELECT * FROM (subquery) WHERE contition,SELECT * FROM table WHERE (subquery LIMIT 1) = 'foo',但不包括SELECT * FROM table WHERE field=(subquery)我尝试了很多方法,这是唯一不抛出异常的方法,但是它不起作用:$curr_user = // id of my user$users = User::where('id', function($query) use($curr_user){ $query->select('wordlists.creator_id') ->from('userlistrels') ->join('wordlists', 'wordlists.id', '=', 'userlistrels.wordlist_id') ->where('userlistrels.user_id', $curr_user); })->get();谁能告诉我这段代码有什么问题,或者如何制作这种类型的子查询?编辑:我的 SQL 查询是错误的。我试图做的正确查询是: SELECT * FROM users JOIN (SELECT wordlists.creator_id FROM userlistrels JOIN wordlists ON wordlists.id=userlistrels.wordlist_id WHERE userlistrels.user_id=$curr_user) AS nn ON users.id=nn.creator_id;并正确的 laravel 代码:$users_sub = DB::table('userlistrels')->join('wordlists', 'wordlists.id', '=', 'userlistrels.wordlist_id')->where('userlistrels.user_id', $curr_user)->select('wordlists.creator_id'); $users = DB::table('users') ->joinSub($users_sub, 'tt', function ($join) { $join->on('users.id', '=', 'tt.creator_id'); })->get();
1 回答
富国沪深
TA贡献1790条经验 获得超9个赞
我认为问题来自您的子查询。该子查询将返回多个creator_id
取决于您的数据库,因此有两种解决方案。
解决方案1:
使用whereIn
代替where
:
User::whereIn('id', function($query) use($curr_user){ $query->select('wordlists.creator_id') ->from('userlistrels') ->join('wordlists', 'wordlists.id', '=', 'userlistrels.wordlist_id') ->where('userlistrels.user_id', $curr_user); })->get();
解决方案2:
limit(1)
后追加where('userlistrels.user_id', $curr_user)
:
User::whereIn('id', function($query) use($curr_user){ $query->select('wordlists.creator_id') ->from('userlistrels') ->join('wordlists', 'wordlists.id', '=', 'userlistrels.wordlist_id') ->where('userlistrels.user_id', $curr_user) ->limit(1); })->get();
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消