Laravel 5.6存储资源后更新数据库中的外键

时间:2019-05-29 06:37:57

标签: php laravel eloquent

我有一个资源“ imagerequest”和一个资源“ events”。对于每种资源,我都有一个模态,其关系如下:

1个Imagerequest可以有很多事件:

图像请求模型:

/**
 * Get the events for an Image Request.
 */
public function events()
{
    return $this->hasMany('App\Event');
}

事件模型:

/**
 * Get the Image Request that belongs to the Event
 */
public function imagerequest()
{
    return $this->belongsTo('App\ImageRequest');
}

现在在创建新的Imagerequest时在表单中有另一个表单可以创建多个事件,但是我的问题是当我存储新事件时没有image_request_id,因为新的image_request_id还不存在,因为我还没有创建图像请求尚未完成。

因此在我的数据库中,image_request_id始终为空

id user_id image_request_id location trainnr created_at  updated_at
1  53      NULL             location NULL    2019-05-28  10:49:45 2019-05-28 10:49:45

保存图像请求以填充此image_request_id后,我是否需要编写更新查询?

我如何在EventController中创建新事件:

$event = Auth::user()->events()->save(new Event($request->all()));

如何在ImagerequestController中创建新的Imagerequest:

$imageRequest = new ImageRequest(
    array_merge(
        $request->all(),
        ['status' => self::STATUS_NEW]
    )
);

$imageRequest = Auth::user()->imageRequests()->save($imageRequest);

编辑我的前端以添加事件

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要添加关系

have a look at the docs for more help with this

从我的快速浏览中,您可以执行以下操作:

$event = Auth::user()->events()->save(new Event($request->all()));

$imageRequest = new ImageRequest(
    array_merge(
        $request->all(),
        ['status' => self::STATUS_NEW]
    )
);

$event->imagerequest()->create($imageRequest);

我还建议您在更新数据库之前先验证所有请求数据。

根据更多信息进行编辑

然后您可以执行以下操作:

$imageRequest->attach($request->eventIds);
相关问题