|
数据库结构4 h( u7 E" n" L5 l+ T% e$ d2 c
name :id, name
7 t- C/ {8 Y! J/ E3 A% J" Uusername :id, username; Y9 Z# d! T9 T! q
user_items :id, user_id, item_id) b/ B# f7 ? F0 s
我目前在count()上user_items显示了拥有最多项目的用户:. }4 G- x6 n& n2 j3 t
john: 13+ S7 r+ q, ]: V3 W; \
bill: 9
# ^& t d' x# U6 h7 q- |lily: 9
$ X+ c; Z. R" Q8 Z7 v/ Ikent: 97 I7 Z8 Y( z- l* Z
seth: 88 ]" k* G5 n0 U/ L/ ^% i; u
vick: 8
9 c1 M5 _" ?1 i# ?anna: 76 `5 ~, N' J+ F& t
但是我想以这种方式显示它:
! j& I1 C' x% \" C13: john
# D$ i4 W- K1 D, y0 V5 z! h* |- x, k1 l 9: bill, lily, kent0 ^- `# r, s( |% u) Y
8: seth, vick
7 s y4 z; p% b9 ? 7: anna0 E$ [) s. T5 c! r" O
如何在刀片服务器中使用laravel的查询系统来实现此目的?
8 h- W3 H" c( H; c+ o 5 c, `9 l, L( G" K6 b" E. ?. U
解决方案:
- ?- {: n! `! a* c. x |' m 1 f' G- e) a8 \8 Q7 _
7 j0 o8 i' f0 j% d8 Z. v4 e- A/ s3 `
% `% T* ]! R: F# c5 l2 \# R7 d \; j 在控制器中得到这样
' K5 ^. q: n/ `/ C9 ^7 O$users = DB::table('user_items as ui')& u/ o M8 V" Z0 y+ E; b( e
->select('count',DB::raw("group_concat(name SEPARATOR ', ') as names"))& E. F* } C" Q8 g! F- {
->from(DB::raw('(select count(*) as count,u.username as name from user_items ui join users u on u.id=ui.user_id group by u.id) a'))
) C& n6 M& ^# o$ E5 Q1 e ->groupBy('count'); ]4 h) B5 M9 L( S1 S3 P
->orderBy('count','desc')
9 ^, Y5 X7 G! [, F" V ->get();! y& T% x$ M+ H( l1 N7 h4 p
$data['users']=$users;
+ }# x7 S; Z2 _9 Vreturn View::make('hello',$data); D l! p1 \& }; t# t7 q
在视图中使用刀片
( C. H/ w. Q0 i7 L d1 G5 i@foreach($users as $user)
3 _+ I) M n7 o: H- a1 Y- D6 Y& [ {{$user->count.':'. $user->names}}
3 |: e1 W% V- T$ Z8 E" W@endforeach
' i2 Y! o+ H+ f. o' ?如果希望不显示任何项目的用户,则可以查询& ]2 d( s& C& y5 y
$users = DB::table('users as u')3 M. e4 p6 Y Q! N0 w& [
->select('count',DB::raw("group_concat(name SEPARATOR ', ') as names"))
4 B+ p; g: K( @( m ->from(DB::raw('(select count(ui.item_id) as count,u.username as name from users u left join user_items ui on u.id=ui.user_id group by u.id) a'))
3 g3 @% D5 q; W) l ->groupBy('count')
, R3 f0 y1 H* n% v; Q* e: e; { F ->orderBy('count','desc')
. e/ ~0 e- C0 g! d ->get();0 ]" l& D$ m8 L4 O7 [: h/ f
要单独显示名称,请在前面添加以下代码 $data['users']=$users;8 ]1 t7 _8 r! o
foreach($users as $user){5 {7 C5 {8 L2 R, q, {
$user->names=explode(', ',$user->names);, W) ]% z2 i/ j8 d( B
}
3 W6 f0 J1 Q8 A& l" s& c而在刀片中,您可以
* L! v. f6 A' F6 `1 \7 v5 d$ ]! {! l |
@foreach($users as $user)
7 y: I# u; ~- x9 R - S% u( C, C* Q
{{$user->count}}:
& O% {! b2 n8 |. w9 u1 P2 z' c1 e @foreach($user->names as $index=>$name)
/ N# h/ ~: y3 f$ h {{$name}} @if($index!=count($user->names)-1) ,@endif + C1 t. ]7 e1 \$ T6 [; a1 P8 f
@endforeach
3 Z8 o% {+ k& D, K1 ?5 u
6 i; K. V4 R$ M. h) L& k @endforeach
; E, l- I. d) n1 c, k3 y! M% i |
|