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 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入