Code Worm
Code Worm

Reputation: 323

How to insert into a table based on an Eloquent relationship an array of foreign keys

I have two models TeamMember and ProjectRequest.

A TeamMember can have one ProjectRequest, that is why I created the following Eloquent relationship on TeamMember:

class TeamMember extends Model {
 //
 protected $table = 'team_members';
 protected $fillable = ['project_request_id'];

 // Relations
 public function projectTeam() {
 return $this->hasOne('\App\Models\ProjectRequest', 'project_request_id');
}
}

In my Controller I want to query both tables, however it returns the failure message.

What is important to know is that $request->projectTeam is an array of emails, looking like this:

array:2 [
       0 => "[email protected]"
       1 => "[email protected]"
       ]

Meaning that I need to bulk insert into team_members table the project_request_ id for each team member where the emails are in the array.

How can I do that in the right way? The following is my attempt:

 public function createProjectTeam(Request $request){
    try {
        $title = $request->projectTitle;
        $TeamMember = $request->projectTeam;
        $projectRequest = ProjectRequest::create(['project_title' => $title]);
        $projectRequestId = $projectRequest->id;
        $projectTeam = $this->teamMembers->projectTeam()->create(['project_request_id'=> $projectRequestId])->where('email', $TeamMember);
        //$projectTeam = TeamMember::createMany(['project_request_id' => $projectRequestId])->where($TeamMember);
        //dd($projectTeam);
        return $projectRequest.$projectTeam;

    } catch(\Exception $e){
        return ['success' => false, 'message' => 'project team creation failed'];
    }

}

Upvotes: 0

Views: 52

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

There are a few things you can do.

Eloquent offers a whereIn() method which allows you to query where a field equals one or more in a specified array.

Secondly, you can use the update() method to update all qualifying team members with the project_request_id:

public function createProjectTeam(Request $request)
{
    try {
        $projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);

        TeamMember::whereIn('email', $request->projectTeam)
             ->update([
                 'project_request_id' => $projectRequest->id 
             ]);

        return [
            'success'      => true,
            'team_members' => $request->projectTeam
        ];


    } catch(\Exception $e) {
        return [
            'success' => false,
            'message' => 'project team creation failed'
        ];
    }
}

I hope this helps.

Upvotes: 1

Related Questions