Reputation: 83
I have the following setup in Laravel - a client who can have many reports which contains many rows of data
Client Object (can have many reports)
class Client extends Model
{
public function reports()
{
return $this
->belongsToMany('App\Report')
->withTimestamps();
}
}
Report Object (can have many rows of data)
class Report extends Model
{
public function data()
{
return $this
->belongsToMany('App\Data', 'report_data')
->withTimestamps();
}
}
Data Object (belongs to a report)
class Data extends Model
{
public function report()
{
return $this
->belongsTo('App\Report')
->withTimestamps();
}
}
If i want to fetch a report for a client i can do this (if i wanted to grab the first one):
$report = $client -> reports -> first();
var_dump($report -> data); die;
That would give me all the data for the first report
Or:
foreach($client -> reports as $report){
var_dump($report -> data);
}
Now the question is - if a client had 3 reports how could i get all the data combined for those 3 reports?
So for example if a client had 3 reports like:
Report 1
Name: test
View: 100
Revenue: 10
Report 2
Name: foo
Views: 50
Revenue: 30
Report 3
Name: bah
Views: 40
Revenue: 20
We could get:
Name: Total
Views: 190
Revenue: 60
I have tried looping over the reports and merging them into one collection but it doesn't work
$reports = $client -> reports -> all();
$collection = new \Illuminate\Database\Eloquent\Collection;
foreach($reports as $report){
$collection = $collection -> merge($report -> data);
}
var_dump($collection);
die;
The relationship has got me a little stumped
Upvotes: 2
Views: 2822
Reputation: 1844
In Laravel, you can use Eager Loading to get the model with related data. If you already have the model and want it's related data, you can use Lazy Loading
$client->load('reports.data');
After that you can check the content with
dd($client);
For getting the total of views, you can do
$totalViews = $client->reports->sum('views');
Since you will be working with Collections
And you will see the relations
field populated with all the reports and, inside them, all the data results for each one.
EDIT
If you want all the data in one place, you can use
$allData = $client->reports->pluck('data');
Also, have in mind that maybe Laravel hav the attribute data
reserved in the models, so if you continue having troubles, try changing that relation name for something like reportData
and the model ReportData
.
Upvotes: 2
Reputation: 4826
try this
$reports = [];
foreach($client -> reports as $report){
$reports [] = $report->data;
}
var_dump($reports);
Upvotes: 0