多对多形式绑定

时间:2014-09-28 01:52:33

标签: laravel laravel-4 eloquent

如何将输入与多对多关系数据绑定?

我的关系是:Model有很多DamagesDamage有很多Models。在数据透视表中存在price字段。 我需要使用price数据填充输入。

{{ Form::input('number', "prices[{$model->id}][{$damage->id}]") }}

我的模特:

class Model extends \BaseModel {

    public function damages()
    {
        return $this->belongsToMany('Damage', 'prices_damages', 'model_id', 'damage_id')
                    ->withPivot('price')
                    ->withTimestamps();
    }

}

数据透视表

Schema::create('prices_damages', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('model_id')->unsigned();
    $table->integer('damage_id')->unsigned();
    $table->float('price')->nullable();
    $table->timestamps();
});

控制器

/**
 * Display a index dashboard page.
 * 
 * @return \Illuminate\Http\Response
 */
public function getDamages()
{
    $models = \Model::orderBy('order')->get();
    $damages = \Damage::orderBy('order')->get();

    return $this->render('Avarias', 'prices.damages', compact('models', 'damages'));
}

查看:

<table class="table-striped table-header-rotated">
    <thead>
        <tr>
            <th></th>
            @foreach ($damages as $damage)
            <th class="vertical"><div><span>{{ $damage->name }}</span></div></th>
            @endforeach
        </tr>
    </thead>
    <tbody>
        @foreach ($models as $model)
        <tr>
            <td>{{ $model->fullname }}</td>
            @foreach ($damages as $damage)
            <td>
                {{ Form::input('number', "prices[{$model->id}][{$damage->id}]", null, ['min' => 0, 'step' => 0.01]) }}
            </td>
            @endforeach
        </tr>
        @endforeach
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

你不能绑定一个集合(在laravel表单模型绑定的意义上),所以你可以这样做:

@foreach ($model->damages as $damage)
  {{ Form::input('number', "damages[{$damage->id}][price]", $damage->pivot->price) }}
@endforeach