Jim E Russel
Jim E Russel

Reputation: 495

Laravel - Table with two columns, each has ID from different tables

I need to create a single objective that has a multi-select drop down wherein different departments can share that same objective. I wanted to create a relationship table with an output like this.

Department Table
id | name
1    Science Department
2    Math Department
3    Biology Department

Objective Table
id | name
1    Be the best

Relationship Table
objective_id | department_id
1              1
1              2
1              3

This is what I think of inside the controller.

public function store(Request $request) {
    $objective = Objective::updateOrCreate(
      [ 'id' => $request->id ?? null ],
      [ 'name' => $request->name ]
    );

    // From multiple select drop down
    foreach($request->departments as $department) {
      RelationshipTable::updateOrCreate(
        [ // what should be the case? ],
        [
          'objective_id' => $objective->id,
          'department_id' => $department['id'],
        ]
      );
    }
  }

I'm not sure on how I would define this in the Model and how I could call their relationship inside the resource. I even think that my controller is wrong or are there better ways to achieve this?

Upvotes: 0

Views: 426

Answers (1)

void
void

Reputation: 913

First You are running query under loop is a very bad process.. may this process will help u? change it as your need!

public function store(Request $request) {
    $objective = Objective::updateOrCreate(
      [ 
       'id' => $request->id ?? null,
       'name' => $request->name
      ]
    );

    // From multiple select drop down
    $insert_array = [];
    foreach($request->departments as $department) {
       array_push($insert_array,[
                                   'objective_id' => $objective->id,
                                   'department_id' => $department['id'],    
                                ]);
    }
    RelationshipTable::updateOrCreate($insert_array);
}

//Relationship Should Be Like in this example Relationship Model

public function object() {
    return $this->hasOne('Model Class of Object' , 'objective_id ' , 'id')
}
public function depertment() {
    return $this->hasMany('Model Class of depertment' , 'department_id' , 'id')
}

Upvotes: 1

Related Questions