doqw89029 2015-11-24 15:59
浏览 80
已采纳

Laravel - 使用单个表单将数据发布到多个表

Let's say I have this form (linked to a named route) that contains 3 text inputs :

{!! 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') !!}

the route calls this function on my controller:

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

Always as example, let's say I have 2 tables : domains to store my domains, and servers to store my servers info (1st and second text input) actually I managed to do the inserts on my first table using the controller mentioned above. my question is how can I do the inserts on the 2 tables via a single submit on my form? how to deal with a Request and a controller for each table ?

this is what i did so far :

1 - i have already have 2 related models (Serverand Domain):

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 - I'm using eloquent, and my tables are related.

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

The documentation does not show how to insert related models using a form. thanks for your help :)

  • 写回答

1条回答 默认 最新

  • duan20145 2015-11-24 17:41
    关注

    Here is how I would handle this. I'm assuming srv_prefix and srv_ip both are attributes of 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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?