Home > Net >  Copy already created data to pivot table in many to many relationship
Copy already created data to pivot table in many to many relationship

Time:05-11

I have 2 tables and pivot table for them model Applicant with relationship many to many

public function contests() {
        return $this->belongsToMany(Contest::class);
    }

model Contest with relationship many to many

public function appcontests() {
        return $this->belongsToMany(Applicant::class);
    }

pivot table applicant_contest with applicant_id and contest_id

It works if I create new applicant and sync or attach contest_id. But I want insert their id's to pivot table after applicant submitted. So that time applicant and contest already created. I get needed applicant and contest and I want insert to pivot table.

  public function saction(Request $request, $user_id){
        if($request->ajax()) {
            
            $post = Applicant::where('user_id', $user_id)->update([
                'appuserstatus_id' => 8
            ]); 
            $post = Applicant::where('user_id', $user_id)->first();

            
            $post->contests()->attach($user_id);
            $post->save();

            return response()->json(['code' => 200, 'msg' => 'Ваша заявка подано', 'user_id'=>$user_id]);
        }
    }

When I submit I call upper function and change appuserstatus_id, and here I try to insert in pivot table, it is the place, where I stuck

CodePudding user response:

There's two ways to achieve this. Your attach method is fine. Second approach just by raw input from Query Builder using Insert

DB::table('your_pivot')->insert(['your column' => $value, 'another column' => $anotherValue]);

CodePudding user response:

I found my error in code. I tried attach $user_id, not contest_id. It was my fault. I just changed it works fine

 $contest = Contest::all();
 $post->contests()->attach($contest);
  • Related