【问题标题】:Laravel - Posting Data to multiple tables with a single formLaravel - 使用单个表单将数据发布到多个表
【发布时间】:2016-02-27 04:02:08
【问题描述】:

假设我有一个包含 3 个文本输入的表单(链接到命名路由):

{!! Form::open(['route' => 'domain.store'])!!}
{!!  Form::text('srv_prefix',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('srv_ip',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('domain',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::submit('create') !!}

路由在我的控制器上调用这个函数:

public function store(CreateDomainRequest $request, Domain $domain)
{
    $domain->create($request->all());
    return redirect()->route('domain.index');
}

总是作为例子,假设我有 2 个表:domains 存储我的域,servers 存储我的服务器信息(第一个和第二个文本输入)实际上我设法在我的第一个表上使用上面提到的控制器。我的问题是如何通过我的表单上的一次提交来插入 2 个表?每个表的一个Request和一个controller如何处理?

这是我到目前为止所做的:

1 - 我已经有 2 个相关模型(ServerDomain):

Class Server extends Eloquent {
    public function domain(){
    return $this->belongsTo('Domain');
    }
// $fillable and stuff..
}

-

Class Domain extends Eloquent {
    public function servers(){
    return $this->hasMany('Server');
    }
//
}

2 - 我正在使用 eloquent,并且我的表是相关的。

    Schema::table('servers', function($table){
        $table->foreign('id_domain')
            ->references('id_dom')
            ->on('domains')
            ->onDelete('cascade');
    });

documentation 没有显示如何使用表单插入相关模型。谢谢你的帮助:)

【问题讨论】:

  • 我所做的是创建一个命令/作业,它将所有内容存储在特定请求中,我需要相应地从我的控制器调度命令/作业。

标签: php laravel laravel-5 eloquent laravel-5.1


【解决方案1】:

这就是我将如何处理这个问题。我假设srv_prefixsrv_ip 都是Server 的属性。

public function store(CreateDomainRequest $request, Domain $domain, Server $server)
{
    // Since domain is the parent, we need to start there.
    $domain = $domain->create($request->all());

    // Now you can create the server model
    $server->fill([
        'prefix' => \Input::get('srv_prefix'),
        'ip' => \Input::get('srv_ip')
    ]);

    // Now we can attach the server to the domain
    $domain->servers()->save($server);

    return redirect()->route('domain.index');
}

【讨论】:

  • 感谢您的帮助。这似乎是正确的做法。但是由于我的servers 表上有一个FK(这是domaintable 的id)我不断收到此错误SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'domain_id' cannot be null (SQL: insert into 'servers' ('domain_id', 'updated_at', 'created_at') values (, 2015-11-25 10:55:45, 2015-11-25 10:55:45)) 我的商店功能看起来像:$vip->create($request->all()); $pool->vip()->associate($vip); $pool->save(); $pool->create($request->only(['srv_hostname','srv_ip','srv_port']));
  • 糟糕,我认为您应该在 Server 模型上使用 fill 而不是 create。这样,在您知道domain_id 将是什么之前,它实际上不会保存。我已经更新了答案。
  • 我不认为问题出在 create 上:我评论了整行,我现在只有 $domain->create($request->all());$server->domain()->associate($domain);$server->save(); 但 Laravel 设法生成正确的查询,但缺少 FK
  • 将您的答案标记为正确答案。并开始了一个新的:stackoverflow.com/questions/33916181/…,因为这是一个不同的问题。
猜你喜欢
  • 1970-01-01
  • 2017-11-05
  • 2013-04-18
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
相关资源
最近更新 更多