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

问题描述 投票:0回答:1

我正在Laravel写查询,但它给了我错误说

ErrorException:类stdClass的对象无法转换为字符串

$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();
php laravel laravel-5 laravel-query-builder laravel-5.8
1个回答
0
投票

在下面的查询中

$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之类的

$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();
© www.soinside.com 2019 - 2024. All rights reserved.