如何在保存的同时将主键值存储到外键

时间:2019-05-31 06:35:31

标签: laravel-5 eloquent

我不熟悉laravel,并尝试将patientid主键值存储到地址表中的patient_id外键

$patdet = $request->patdet;

foreach ($patdet as $patdets) {
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname = $patdets['mname'];
    $pdet->lname = $patdets['lname'];
    $pdet->age = $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender = $patdets['gender'];
    $ptid = $pdet->save();
}

$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();

我知道$ptid是局部变量,不能在地址表中使用,那么如何将其存储在地址表中?

2 个答案:

答案 0 :(得分:1)

尝试以下方法,然后问我是否无效

foreach($request->patdet as $key => $patdets)
{
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname =  $patdets['mname'];
    $pdet->lname =  $patdets['lname'];
    $pdet->age   =  $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender  = $patdets['gender'];
    $pdet->save();
    $addr = $request->address[$key];
    if($pdet->id > 0 && !empty($addr)){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = $pdet->id;
        $addrss->save();
    }
}

答案 1 :(得分:0)

尝试以下

    $patArray = $request->patdet;
    $addressArray = $request->address;
    $pId = array();
    foreach($patArray as $key => $patdets){
        $pdet = new Patient();
        $pdet->fname = $patdets['fname'];
        $pdet->mname =  $patdets['mname'];
        $pdet->lname =  $patdets['lname'];
        $pdet->age   =  $patdets['age'];
        $pdet->blood_group = $patdets['bloodgroup'];
        $pdet->gender  = $patdets['gender'];
        $pdet->save();
        $pId[$key] = ($pdet->id > 0) ? $pdet->id : 0;
    }
    foreach($addressArray as $key => $addr){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = array_key_exists($key ,$pId) ? $pId[$key] : 0;
        $addrss->save();
        $i++;
    }