How to insert data into a table that has multiple Foreign key and relates to other 4 tables using Laravel with Eloquent?

Asked

Viewed 129 times

-1

I have a table that has 4 foreign Keys and relates to 4 other tables. I would like to know how I would insert all the records, coming in Request, in this table, including your Foreign key. I’m a little lost in the model’s store() method and with the use of Eloquent for this situation.

Data, including Foreign key values, would come in Request.

OBS: I’m using Relationship Onetomany in all these tables.

I’ll leave a table print (task_lists) in the database.

inserir a descrição da imagem aqui

  • I will leave some links of my code not to pollute here and the question does not get too extensive.

Migration

Routes

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Recurrence; //Chamando a model Recurrence (inserido)
use App\Models\User; //Chamando a model User (inserido)
use App\Models\TaskType; //Chamando a model TaskType (inserido)
use App\Models\Status; //Chamando a model Status (inserido)

class TaskList extends Model
{
   //Dados que podem ser inseridos em massa na tabela
    protected $fillable = [     
        'number_of_process',
        'expire_day',
        'expire_date', 
        'start_date', 
        'end_date',            
        'details',      
    ];


    //Dados que não podem ser inseridos em massa
    protected $guarded = [        
        'recurrence_id',    
        'concluding_user_id',  
        'task_type_id', 
        'status_id',         
    ];

    public function rules()
    {
        //As regras de cada campo
        return [        
            'recurrence_id' => 'required',
            'concluding_user_id' => 'required',
            'task_type_id' => 'required',
            'status_id' => 'required',
            'number_of_process' => 'required',
            'expire_day' => 'required',
            'expire_date' => 'required',                        
        ];
    }  

    //Criando o relacionamento com a model(tabela) Recurrence (Muitos para 1)
    public function recurrence()
    {
        return $this->belongsTo(Recurrence::class);        
    }

    //Criando o relacionamento com a model(tabela) User (Muitos para 1)
    public function user()
    {
        return $this->belongsTo(User::class);        
    }

    //Criando o relacionamento com a model(tabela) TaskType (Muitos para 1)
    public function taskType()
    {
        return $this->belongsTo(TaskType::class);        
    }

    //Criando o relacionamento com a model(tabela) Status (Muitos para 1)
    public function status()
    {
        return $this->belongsTo(Status::class);        
    }
}

?>

Controller

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use App\Models\Recurrence; 
use App\Models\User; 
use App\Models\TaskType; 
use App\Models\Status; 
use App\Models\TaskList;


class TaskListController extends BaseController
{
    protected $request; 
    protected $recurrence;
    protected $user;
    protected $taskType;
    protected $status;   
    protected $model;

  
    //Injeção de Dependência
    public function __construct(Request $request, Recurrence $recurrence, User $user, TaskType $taskType, Status $status, TaskList $TaskList)
    {
        
        $this->request = $request;
        $this->recurrence = $recurrence;   
        $this->user = $user; 
        $this->taskType = $taskType; 
        $this->status = $status;  
        $this->model = $taskList;
       
    }


     //use AuthorizesRequests, DispatchesJobs, ValidatesRequests;  

    //Mostra todos os dados de uma determinada Tabela
    public function index()
    {
         $data = $this->model->all();
         return response()->json($data);
    }

  

    //Grava dados em uma determinada Tabela
    public function store(Request $request)
    {

        $request->validate($this->model->rules());
        $dataForm = $request->all(); //Dados que vem da requisição

        $recurrence = $this->recurrence->find($dataForm['recurrence_id']);
        $user = $this->user->find($dataForm['user_id']);
        $taskType = $this->taskType->find($dataForm['task_type_id']);
        $status = $this->status->find($dataForm['status_id']);

        $data = [           
            'task_name' => $dataForm['task_name'],
            'details' => $dataForm['details'],                       
        ];

        $recurrence->recurrence()->create($data);  
        $user->user()->create($data);
        $taskType->taskType()->create($data);
        $status->status()->create($data);  

        return response()->json($dataForm, 201);
        
    }  
   
}

?>

In short: I’d like to insert all the records into this table only I’m not finding the correct shape because of the four Foreign key. Usually I can do when the table relates to only one other table.

1 answer

1


public Function store(Request $request) {

    $request->validate($this->model->rules());
    $dataForm = $request->all(); 

    $taskList = new TaskList ;

    $recurrence = $this->recurrence->find($dataForm['recurrence_id']);

    $user = $this->user->find($dataForm['user_id']);

    $taskType = $this->taskType->find($dataForm['task_type_id']);

    $status = $this->status->find($dataForm['status_id']);



    $taskList->task_name = $dataForm['task_name'];
    $taskList->details = $dataForm['details'];

    $taskList->recurrence()->associate($recurrence);
    $taskList->user()->associate($user);
    $taskList->taskType()->associate($taskType);
    $taskList->status()->associate($status); 
    
    $taskList->save();
    

    return response()->json($dataForm, 201);
    
}  
  • It worked right for me, Luciano. Thank you very much. You could explain to me better the functioning of this association() ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.