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

时间:2019-04-27 12:55:32

标签: php laravel laravel-5 laravel-query-builder laravel-5.8

我正在用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();

1 个答案:

答案 0 :(得分: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_id匹配,则应使用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();