How to bring the relationships of a certain model to display them in a table with Inertia::render?

Viewed 271

I'm trying to get the relationships for a model from the controller so be able to display the relationship not as a id but as that id's name or type or whatever it might be. In this case I'm trying to get information relating to a question, what response type it has (text, multiple, rank, yes or no) and also which section is belongs to (the name)

This is my controller code so far

public function index()
{
    return Inertia::render('Question/Index', [
        'survey_question' => SurveyQuestion::all(),
        'survey_section' => SurveySection::all(),
        'response_type' => ResponseType::all()
    ]);
}

The table in the vue

<el-table
    :data="tableData">
    <el-table-column
        prop="question"
        label="Pregunta">
    </el-table-column>

    <el-table-column
        label="Seccion">
        <template slot-scope="scope">
            <p> {{ scope.row.survey_section.title }} </p>
        </template>
    </el-table-column>

    <el-table-column
        label="Tipo de Respuesta">
        <template slot-scope="scope">
            <p> {{ scope.row.response_type.type }} </p>
        </template>
    </el-table-column>

    <el-table-column
        prop="optional"
        label="Opcional">
    </el-table-column>

    <el-table-column>
        <template slot-scope="scope">
                <div class="btn-link-edit action-button" @click="edit(scope.row)">
                    <i class="fas fa-pencil-alt"></i>
                </div>
                <div class="btn-link-delete action-button" @click="delete(scope.row)">
                    <i class="fas fa-trash"></i>
                </div>
        </template>
    </el-table-column>
</el-table>

This brings the relationships I think, because when I create a new question I have a select option and it does show the names instead of the ids, but when I'm trying to display said name in a table I can only access the id.

I also would like to know how to show for the optional field instead of 0 or 1, yes or no. This field is a boolean in the table structure if that is important.

If I do {{ scope.row }} then I get the information but only of the question like this

{ "id": 1, "question": "asdfasdf", "survey_section_id": 1, "response_type_id": 1, "optional": 1 }

What I would like is that when I do {{ scope.row }} I also get from those ids another array with the information related to that id both from the section and the response type.

1 Answers

You should use with method in the eloquent model. For example:

$result = Model::with(['nameOfTheRelationShip'])->get();
Related