简体   繁体   English

Laravel 5数据透视表额外字段

[英]Laravel 5 Pivot Table Extra Field

What I'm trying to do is when a new candidate is created an extra field is automatically populated in the joining pivot table with a random sting. 我想做的是,当创建一个新的候选人时,一个额外的字段会自动填充到连接数据透视表中,并带有一个随机的字符串。

Here is my pivot table: 这是我的数据透视表:

Result Table (pivot) 结果表(数据透视)

id  cert_number candidate_id    qualification_id
1   ?           17              2
2   ?           17              1
3   ?           57              1

So in my candidate controller I have: 所以在我的候选控制器中,我有:

public function store(CandidateRequest $request)
{
    $candidateInput = Input::get('candidates');


    foreach ($candidateInput as $candidate)
    {
        $candidate = Candidate::create($candidate);

        $candidate->centre()->attach(Auth::user()->centre);

        $qualification_id = $request->input('qualification_id');

        $candidate->qualification()->attach($qualification_id);

        $cert_number = Str::random(10);

        $candidate->qualification()->attach($cert_number);

    }

    return redirect('candidates');
}

It adds the centre_id and qualification_id perfectly but it won't pull though the random sting into the cert_nubmer field. 它完美地添加了center_id和qualification_id,但不会将随机字符串插入cert_nubmer字段。

In my Candidate model I have 在我的候选人模型中,

public function result()
{
    return $this->hasMany('App\Result')->withTimestamps();
}

public function qualification()
{
    return $this->belongsToMany('App\Qualification', 'Results', 'candidate_id', 'qualification_id')->withPivot('status','cert_number','partial_claim')->withTimestamps();
}

and in my result model: 在我的结果模型中:

public function candidate()
{
   return $this->belongsTo('App\Candidate')->withTimestamps();
}

public function qualification()
{
   return $this->belongsTo('App\Qualification');
}

Can anyone see where Im going wrong? 谁能看到我的问题出在哪里?

Thanks. 谢谢。

attach does not work like that. 附加不能那样工作。

Let me take out two lines of code: 让我取出两行代码:

$candidate->qualification()->attach($qualification_id);
$candidate->qualification()->attach($cert_number);

You are trying to add the $cert_number as a qualification_id, which is why it fails. 您试图将$ cert_number添加为qualification_id,这就是为什么它失败的原因。 When you do this, how is Laravel supposed to know that the second line ($cert_number) is an extra pivot column? 当您这样做时,Laravel应该如何知道第二行($ cert_number)是一个额外的数据透视列? It doesn't. 没有。 You have two lines of code that are exactly the same so you can't expect Laravel to know that the second line should do something different. 您有两行代码完全相同,因此您不能期望Laravel知道第二行应该做一些不同的事情。

When you want to insert extra data into other pivot columns, you need to pass them as an array in the second argument. 当您要将额外的数据插入其他数据透视表列时,需要将它们作为数组传递给第二个参数。 Something like this: 像这样:

$candidate->qualification()->attach($qualification_id, ['cert_number' => $cert_number]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM