我有以下数据模式

Detalle_Servicio有许多Material_Usado并且Material_Usado只属于Detalle_Servicio
当我在材料中保存值时,Usado应该知道ID Detelle_Servido,但由于我不能这样做。我有以下代码
路线

Route::post('/upload', function(){

    $path = public_path().'/servicios';
    try{
        $upload_success1 = Input::file('foto1')->move($path,'1');
        $upload_success2 = Input::file('foto2')->move($path,'2');
        $upload_success3 = Input::file('foto3')->move($path,'3');
        $upload_success4 = Input::file('foto4')->move($path,'4');
    }catch(Exception $e) {
        $e->getMessage();
    }
    $input = Input::get('json');
    $json = json_decode($input);

    if($upload_success1 && $upload_success2 && $upload_success3 && $upload_success4) {
        //DB::insert("INSERT INTO Detalle_Servicio (RutaFoto1, RutaFoto2, RutaFoto3, RutaFoto4, FechaTermino, Latitud, Longitud, Servicio_idServicio) values(?,?,?,?,?,?,?,?)", array($path.'1', $path.'2', $path.'3', $path.'4',$json->termino, $json->latitud, $json->longitud, $json->idServicio));
        $entradas = array(
                    'RutaFoto1' => $path.'1',
                    'RutaFoto2' => $path.'2',
                    'RutaFoto3' => $path.'3',
                    'RutaFoto4' => $path.'4',
                    'FechaTermino' => $json->termino,
                    'Latitud' => $json->latitud,
                    'Longitud' => $json->longitud,
                    'Servicio_idServicio' => $json->idServicio
                    );
        Detalle_Servicio::create($entradas);

       $array = array('Code' => '202', 'Message' => 'Done');
       return Response::json($array);
    } else {
        $array = array('Code');
       return Response::json('error', 400);
    }


 });

可以看到,我得到了一个JSON,其中包含我存储在数据库中的值
我将数据保存在Detalle_Servicio表的数据库中,但是我需要在Material _Usado中保存一些数据,但是我需要在将数据保存在Detalle_Servicio表中时生成的ID
模型
class Detalle_Servicio extends Eloquent{
protected $table = 'Detalle_Servicio';
protected $primaryKey = 'idDetalle_Servicio';
protected $fillable = array('RutaFoto1', 'RutaFoto2', 'RutaFoto3', 'RutaFoto4', 'FechaTermino', 'Latitud', 'Longitud', 'Servicio_idServicio');


public function servicio(){
    return $this->belongsTo('Servicio', 'idServicio'); //le pertenece a
}
public function material_usado(){
    return $this->hasMany('Material_Usado', 'idMaterial_Usado');
}
}


class Material_Usado extends Eloquent{
protected $table = 'Material_Usado';
protected $primaryKey = 'idMaterial_Usado';

public function detalleServicio(){
    return $this->belongsTo('Detalle_Servicio', 'idDetalle_Servicio');
}
}

我该怎么做?

最佳答案

使用时:

Detalle_Servicio::create($entradas);

它返回刚刚创建的模型实例,因此您应该这样做:
$Detalle_Servicio = Detalle_Servicio::create($entradas);

现在,您可以使用以下方法获取创建的模型的id:
$Detalle_Servicio->id;

所以,你可以这样做:
if($Detalle_Servicio = Detalle_Servicio::create($entradas)) {
    $id = $Detalle_Servicio->id;
    // ...
}

10-07 19:38
查看更多