Reputation: 1103
I have two models: Report and User. This is what I have in my User model
public function userReport() {
return $this->hasMany('App\Report', 'user_id','id');
}
And this is in Report model
public function user() {
return $this->hasOne('App\User', 'id', 'user_id');
}
Controller
public function details( $item_id ){
$report = Item::find($item_id)->report;
return view('details', compact('report'));
}
In view
{!! $report->user->name !!}
In view I show all the users who are reported single Item .. which I query by $item_id
.
The problem is that if same user is reported single item 1+ time I see this user 1+ time in the table on the page.
Is it possible to somehow grouped by user_id or count the user_id and show User1 ( 4 time reported )
...? Where should I group them?
Update: users table
id | username | password
reports table
report_id | id | user_id | date
item table
id | user_id | category | date_added | image
Update2: Image of records in db. Here user with user_id=3
has reported item_id=14
total of 14 times. User with user_id=5
has reported same item_id=14
total of 3 times. So I should see on page user_id=3 ( 14 )
and user_id=3 ( 3 )
. Instead I see 17 times user_id=3
. Bellow are images
And on page
Upvotes: 0
Views: 2417
Reputation: 2856
Just try this. Hope it helps
Report::where('item.id', $item_id)
->select('item.*','users.*',DB::raw('count(reports.report_id) as total'))
->join('item', 'item.id', '=', 'reports.id')
->join('users', 'users.id', '=', 'reports.user_id')
->groupBy('reports.report_id','reports.id')
->get();
Upvotes: 1
Reputation: 4610
There should be several ways how to solve your problem
One way is (your controller should look like)
public function details( $item_id ){
$report = Item::find($item_id)->report->unique('user_id');
return view('details', compact('report'));
}
Second way should be to use @foreach
in view and there check for unique values.
Third way should be to use foreach
in controller and prepare unique data with calculated summarizes inside controller and then pass that prepared data to view.
Which soulution you want to use is just a matter of choice.
Hope it helps you
Upvotes: 1