About Ravel Relationships

Asked 2 years ago, Updated 2 years ago, 45 views

If there are three tables in laravel,

If you want to display the department name (section_name) when you print a list of reports. What should I do?

▼Company vehicle report table
CarReport

report_id
car_id
report_data
....

▼Company Car Table
Car

car_id
car_name
section_id
....

▼ Department Table
Section

section_id
sectorn_name

Currently, the following code is written, but
It doesn't show up properly.

class CarReport extensions Model
{
    public function detection()
    {
        return$this->hasManyThrough('App\Car', 'App\Section', 'section_id', 'car_id');
    }
...........

php laravel

2022-09-30 17:29

1 Answers

I don't know the relationship between each data, so please call the official document and rewrite the hasOne part.

Assume that the DB value you got was in $getData if you want to access it with view, Model, or controller.

$getData->carsReports->cars->section_name

If you write , you will get the department name.

It's good to write down exactly what it means that it doesn't display properly.
Is it empty, is there an error screen, and what kind of error is there?

Let's read the official document a little more carefully.Excerpt from laravel 5.5

·The first argument is the model name that you want to access in the end, and the second argument is the model name that you want to mediate.
·The third argument is the foreign key name of the intermediary model and the fourth argument is the foreign key name of the final model.

Based on the source code of the defect, we assumed the CarReport table to start.
Get the section_id from the Car table first, and finally the department name from the Section table,
I think that's the trend.

return$this->hasManyThrough('App\Section', 'App\Car', 'car_id', 'section_id');

How about this?


2022-09-30 17:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.