我有三个表:(用户和单词列表之间的多对多关系,userlistrels 是连接器)
users:
id
name
wordlists:
id
name
creator_id
userlistrels:
id
user_id
wordlist_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();
富国沪深