在 laravel 的 where 子句中使用一个查询结果的方法是什么,就像我们在 sql 查询中使用 where in 子句一样?

What is the way to use the one query result in where clause in laravel like we do in sql query using where in clause?

我正在 Laravel 中编写查询,但出现错误 Saying

ErrorException: Object of class stdClass could not be converted to string

$subject_ids = DB::table('question_sets')
                   ->select('subject_id')
                   ->where('test_section_id','=',$testDetail->test_section_id)
                   ->distinct()
                   ->get();

$topic_ids = DB::table('topics')
                 ->select('id')
                 ->where('subject_id','=',$subject_ids)
                 ->get();

在下面的查询中

$subject_ids = DB::table('question_sets')
                   ->select('subject_id')
                   ->where('test_section_id','=',$testDetail->test_section_id)
                   ->distinct()->get();

你正在获取一个集合,如果你想要一个特定的值,你可以使用first() 然后你可以做

$subject_id = DB::table('question_sets')
                  ->select('subject_id')
                  ->where('test_section_id','=',$testDetail->test_section_id)
                  ->distinct()
                  ->pluck('name')
                  ->first();

$topic_ids = DB::table('topics')
                 ->select('id')
                 ->where('subject_id','=',$subject_id)
                 ->get();

如果你想匹配所有$subject_ids,你应该使用toArray()whereIn like

$subject_ids = DB::table('question_sets')
                   ->select('subject_id')
                   ->where('test_section_id','=',$testDetail->test_section_id)
                   ->distinct()
                   ->pluck('subject_id')
                   ->toArray();

$topic_ids = DB::table('topics')
                 ->select('id')
                 ->whereIn('subject_id', $subject_ids)
                 ->get();