如何在Laravel中获取当前已保存模型的ID

时间:2019-04-09 20:24:05

标签: php laravel

在模型的store()方法上,我想再保存两个模型。我需要存储的当前模型的ID。我该怎么办?

控制器

public function store(Request $request, Property $property)
{
    /*******************************************************
     * Validation sent data
     * Validate e forme ersali user
     *******************************************************/

    $data = $request->validate([
        'type' => 'required',
        'title' => 'required',
        'description' => 'required',
        'base_capacity' => 'required',
        'max_occupancy' => 'required',
    ]);

    Property::create($data);

    PropertyDetail::create([
        'property_id' => 1,
        'state' => $request->state,
        'city' => $request->city,
        'address' => $request->address,
        'post_code' => $request->post_code,
        'placearea' => $request->place_area,
        'telephone' => $request->telephone,
    ]);
}

在这里,我将属性ID硬编码在属性详细信息中。但是,我想获取刚刚在其上面创建的当前属性的ID。

2 个答案:

答案 0 :(得分:3)

好的方法

  1. 创建Property的实例
$property = Property::create($data);
  1. 参考
PropertyDetail::create([
        'property_id' => $property->id, // here it is
        'state' =>$request->state,
        'city' =>$request->city,
        'address' =>$request->address,
        'post_code' =>$request->post_code,
        'placearea' =>$request->place_area,
        'telephone' =>$request->telephone,
    ]);

更安全的方法

更安全的方法几乎完全相同,只是您使用两个查询,并且查询可能失败。您要确保要么成功要么都不成功。为此,我们使用交易。

我们要保证的是确保数据已进入数据库。


public function store(Request $request,Property $property)
{
    /*******************************************************
     * Validation sent data
     * Validate e forme ersali user
     *******************************************************/

    $data = $request->validate([
        'type' => 'required',
        'title' => 'required',
        'description' => 'required',
        'base_capacity' => 'required',
        'max_occupancy' => 'required',
    ]);

    \DB::transaction(function() use ($data, $request) {
        $property = Property::create($data);

        PropertyDetail::create([
            'property_id' => $property->id,
            'state' =>$request->state,
            'city' =>$request->city,
            'address' =>$request->address,
            'post_code' =>$request->post_code,
            'placearea' =>$request->place_area,
            'telephone' =>$request->telephone,
        ]);
    });
}

答案 1 :(得分:1)

您可以使用id方法返回的模型以及您需要的地方,从Property获得create

$property = Property::create($data);
PropertyDetail::create([
        'property_id' => $property->id,
        'state' =>$request->state,
        'city' =>$request->city,
        'address' =>$request->address,
        'post_code' =>$request->post_code,
        'placearea' =>$request->place_area,
        'telephone' =>$request->telephone,
    ]);