我在laravel 5尝试加入我们,但我有一些问题希望你能帮助我,
$results = DB::table('words')
->join('users_words_relationship','users_words_relationship.word_id','=','words.id')
->where('users_words_relationship.user_id','=',Auth::user()->id)
->join('translate','translate.word_id','=','words.id')
->select('words.word','translate.translate')
->get();
此查询确实返回了重复结果
word translation
Hello مرحبا
Hello اهلا وسهلا
Hello مرحبآ
Hello اهلا و سهلا
我试图像这样添加groupBy()
$results = DB::table('words')
->join('users_words_relationship','users_words_relationship.word_id','=','words.id')
->where('users_words_relationship.user_id','=',Auth::user()->id)
->join('translate','translate.word_id','=','words.id')
->groupBy('translate.word_id')
->select('words.word','translate.translate')
->get();
它确实返回了一个结果Hello对,但并没有只有一个翻译!!
喜欢
word translation
Hello مرحبا
答案 0 :(得分:1)
您正在寻找群组连接。
在Laravel中,您的查询将变为
DB::table('words')
-> join('users_words_relationship','users_words_relationship.word_id','=','words.id')
-> where('users_words_relationship.user_id','=',Auth::user()->id)
-> join('translate','translate.word_id','=','words.id')
-> select('words.word', DB::raw('GROUP_CONCAT(DISTINCT translate.translate) as translations'))
-> group_by('words.word')
-> get();
答案 1 :(得分:0)
如果您正在寻找以下输出
字词翻译
Helloمرحبا
Helloاهلاوسهلا
Helloمرحبآ
使用distinct('translate.translate')
这是查询
$results = DB::table('words')
->join('users_words_relationship','users_words_relationship.word_id','=','words.id')
->where('users_words_relationship.user_id','=',Auth::user()->id)
->join('translate','translate.word_id','=','words.id')
->select('words.word','translate.translate')
->distinct('translate.translate')
->get();