我有兩個表'devicelist'和'devicegroup'。設備列表包含accountID,groupID,deviceID。設備組表包含組ID,說明。 在設備列表中,groupID表示組標識碼,deviceID是設備名稱(它是唯一的),同一組ID將爲多個設備重複。 在與設備列表中相同的設備組groupID中,groupID是唯一的,描述是組名。在我的查看頁面中,需要顯示groupID,'devicegroup'表中的描述以及'devicelist'表中每個groupID的設備數。每組中的設備數量需要自動計算而不是在where子句中給出一個groupID。如何在laravel 5.2中爲連接表做sql計數函數
任何人都可以告訴我如何編寫sql查詢,我需要做什麼來獲得這個輸出。 回覆是可觀的。 我試過的查詢在下面給出。
public function getIndex()
{
$vehicleCount=DB::table('devicelist as dev_list')
->select(DB::raw('groupID, dev_group.description, count(*)'))
->join('devicegroup as dev_group', 'dev_list.groupID', '=', 'dev_group.groupID')->get();
echo $vehicleCount;
$groups = DB::table('devicegroup')->simplePaginate(10);
return view('group.groupAdmin')->with('groups',$groups);
}
更新後的查詢。
public function getIndex()
{
$vehicleCount=$vehicleCount=DB::table('devicelist as a')
->join('devicegroup as b', 'a.groupID', '=', 'b.groupID')
->select('b.groupID','b.description',DB::raw('count(a.deviceID)'))
->where('a.groupID','=','b.groupID')
->get();
//echo $vehicleCount;
//$groups = DB::table('devicegroup')->simplePaginate(10);
return view('group.groupAdmin')->with('vehicleCount',$vehicleCount);
}
和我的視圖頁
@extends('app')
@section('content')
<br><br><br><br><br>
<div class="templatemo-content-wrapper">
<div class="templatemo-content">
<ol class="breadcrumb">
<li><a href="{{ url("/") }}"><font color="green">Home</font></a></li>
<li class="active">Group information</li>
</ol>
<h1>View/Edit Group information</h1>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="example" class="table table-striped table-hover table-bordered">
<h3>Select a Group :</h3>
<thead>
<tr>
<th>Group ID</th>
<th>Group Name</th>
<th>Vehicle Count</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($vehicleCount as $grp)
<tr>
<td>{{ $grp->groupID }}</td>
<td>{{ $grp->description }}</td>
<td>{{count($grp)}}</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
{{[email protected] ($nam->isActive == 'Yes')--}}
<li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $grp->groupID }}"><a href="{{ url('/group/edit/'.$grp->groupID) }}">View/ Edit</a>
</li>
{{[email protected]}}
<li><a href="{{ url('/group/delete/'.$grp->groupID)}}">Delete</a></li>
</ul>
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
{{--//{{$groups->links()}}--}}
</div>
</div>
</div>
</div>
</div>
</br>
使用SQL我只想從設備列表中只取每個組ID的設備計數。我正在通過剩餘的組ID和說明。我在我的問題中添加完整的代碼。所以請告訴是否可以發送像這樣或我應該使用相同的SQL查詢發送所有數據。感謝您的寶貴迴應:) –
我已根據您的最新評論更新了答案。對不起,花了我很多時間。 – boroboris
是的,我明白了..謝謝 –