jeudi 22 août 2019

Defining relationships and processing data within them

I have got myself a bit confused with relationships, I am not sure if I am splitting things up too much? I am dealing with a reporting system where there can be different types of reports. So, I have my standard reports table and model, and within the model, I define that a report can have one report type.

public function reportType() {
    return $this->hasOne('App\ReportType');
}

Now a reportType can be one of three different Types, lets call them A, B and C. Each reportType collects different data. As such, within the ReportType model, I define a has one relationship with the type it has

public function reportTypeA() {
    return $this->hasOne('App\ReportTypeA');
}

So the above states that a reportType can have one reportTypeA. I also have in this Model that it can have one reportTypeB and C. Now within reportTypeA model, I state that reportTypeA can have one set of reportTypeAData

public function reportTypeAData() {
    return $this->hasOne('App\ReportTypeAData');
}

I have the inverse relationships in all Models. So essentially, I have

Report->ReportType->ReportTypeA->ReportTypeAData
                    ReportTypeB->ReportTypeBData
                                 ReportTypeBData2
                    ReportTypeC->ReportTypeCData

Reason I have the data models is because some reports have more than one set of data. So the above shows that Report B has 2 sets of data, each with its own structure.

So the above works, but it seems very "waterfall" approach to me. I will clean this up at some point to hopefully make it more structured.

This is where I am confused though, with the above approach, how can I get the data for a Report? So in my controller, I have something like

$report = Report::where('user_id', Auth::user()->id)->first();

This will get me the first report for the logged in User. I can then get the report data doing something like this

$reportData = $report->reportType->reportTypeA->reportTypeAData->all()->toArray();

Which seems proper overkill having to go through all relationships. My main problem is this, I want to chunk the data back to the frontend, so I will have something like this

DB::table("report_type_a_data")->chunk(100, function ($data) use ($handle) {
    foreach ($data as $row) {
        // Add a new row with data
        fputcsv($handle, [
            $row->id,
            $row->name
        ]);
    }
});

Now obviously that will loop all data, where I only want the data for the report I am dealing with. Additionally, when I try this, I get an error

You must specify an orderBy clause when using this function

Why am I getting this? Any help with organising things better and how I can process a specific reports data is highly appreciated.

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire