0

我有两个模型TeamMemberProjectRequest.

ATeamMember可以有一个ProjectRequest,这就是为什么我创建了以下 Eloquent 关系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');
}
}

在我的控制器中,我想查询两个表,但是它返回失败消息。

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

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

这意味着我需要为数组中电子邮件所在的每个团队成员批量插入team_members表格。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'];
    }

}
4

1 回答 1

1

您可以做几件事。

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

我希望这有帮助。

于 2019-04-15T15:29:29.067 回答