Laravel 5.1 - Eloquent关系更新函数

3

我正在使用 Laravel 5.1。

我有两个表格,user表和users_detail表,它们之间有一个oneToOne的关联。我已经成功地将这两张数据表显示在一个表单中。

现在我想在我的控制器中运行update函数。我已经知道如何在我的其他项目中在单个表格中运行update 函数。你们有谁能给我一些线索,如何在单个控制器中运行update两个表格?

我们需要使用 Laravel 的update()函数吗?还是其他什么方式?

我在我的view中使用了这个:

...
{!! Form::model($users, ['method' => 'PATCH', 'route' => 'dashboard.user.update', $users -> id]) !!}
    <div class="form-group">
        {!! Form::label('User ID', 'User ID:') !!}
        {!! Form::text('id', $users->id, $attributes = array('id'=>'disabledInput', 'Disabled', 'class'=>'form-control', 'placeholder'=>'User ID')); !!}
    </div>
...
    <div class="form-group">
        {!! Form::label('Place Of Birth', 'Place Of Birth:') !!}
        {!! Form::text('placeOfBirth', $users->UsersDetail->placeOfBirth, $attributes = array('class'=>'form-control', 'placeholder'=>'Place Of Birth')); !!}
    </div>
...
...
{!! Form::close() !!}
...
2个回答

1
这里有一个不错的技巧,可以一行代码完成所有操作。associate() 用于更新 belongsTo() 关系。
它的工作方式如下:
    $user = User::find($id);
    $record= new User_Detail($request->all());

    $record->user()->associate($user);
    $record->save();

对于多对多关系,您可以使用attach同步模型。

我将以文章为例进行说明。

    $new_article = new Article($request->all());
    $new_article->save(); //I need to save it first so that we the article ID

    Auth::user()->article()->attach($new_artcile->id);

0

终于我找到了一种方法。它并不像我想象的那么困难。

public function update(Request $request, $id) {
    //          
    $usersUpdate = $request->all(); //get all value from form

    $users = User::find($id); //find the primary key of User table
    $usersDetail = UsersDetail::find($id); //find the foreign key UsersDetail table

    $users->update($usersUpdate); //update the User table
    $usersDetail->update($usersUpdate); //update the UsersDetail table

    return redirect('dashboard/user');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接