如何根据 Eloquent 关系向 table 中插入一个外键数组

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

我有两个模型 TeamMemberProjectRequest

一个 TeamMember 可以有一个 ProjectRequest,这就是我在 TeamMember 上创建以下 Eloquent 关系的原因:

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');
}
}

在我的控制器中,我想查询两个 table,但是 returns 失败消息。

重要的是要知道 $request->projectTeam 是一组电子邮件,如下所示:

array:2 [
       0 => "mv@something.com"
       1 => "as@something.com"
       ]

意味着我需要批量插入 team_members table project_request_ id 为电子邮件在数组中的每个团队成员。

我怎样才能以正确的方式做到这一点?以下是我的尝试:

 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'];
    }

}

您可以做一些事情。

Eloquent 提供了一个 whereIn() 方法,允许您查询指定数组中字段等于一个或多个的位置。

其次,您可以使用 update() 方法更新所有符合条件的团队成员 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'
        ];
    }
}

希望对您有所帮助。