Laravel多对多关系存储功能

时间:2017-06-28 15:32:30

标签: php laravel

我在laravel

中有很多关系的问题

我的数据库是愿望清单,包含表朋友,愿望和wish_friend。我的wish_friend表只有wish_id,friend_id和timestamps。

我的模特是:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Wish;

class Friend extends Model
{
    protected $table = "friends";
    protected $primaryKey = "id";
    protected $fillable = array("name", "age");
    public $timestamps = true;

    public function wishes()
    {
        return $this->belongsToMany('App\Wish', 'wish_friend')->withTimestamps();
    }
}

这是我的控制器功能创建和存储

public function create() {
    $wishes = Wish::all();     
    return view("friends.create", compact("wishes"));
}

public function store(Request $dados) {
    $friend = Friend::create($dados->all());

    if(is_null($friend)) {
        return redirect()->route("friend.index")->withErrors("Erro ao criar curso. Por favor, tente novamente.");  
    }
    else {
        return redirect()->route("friend.index")->with("Curso inserido com sucesso!");
    }
}

这是我的朋友查看create.blade

@extends('layouts.master')
@section('content')
<div class="container-fluid">
    <h1>Adicionar uma nova curso</h1>
    <h4>Insira toda a informação sobre a curso.</h4>
    <a href="{{URL::route('friend.index')}}" class="btn btn-default">Voltar atrás</a>
    <hr>

    <form action="{{URL::route('friend.store')}}" method="POST">
        <div class="form-group">
            <label for="name" class="control-label">Nome:</label>
            <input type="text" id="name" name="name" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="age" class="control-label">Age:</label>
            <input type="number" id="age" name="age" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="wish" class="control-label">Wishes:</label>
            <select id="wish" name="wish" class="form-control" multiple required>
                @foreach($wishes as $wish)
                    <option value="<?php echo $wish->id; ?>"><?php echo $wish->name; ?></option>
                @endforeach
            </select>
        </div>
        <input type="submit" class="btn btn-primary" value="Inserir">
        <input type="hidden" name="_token" value="{{csrf_token()}}">
    </form>
</div>
@stop

当我选择愿望时如何插入wish_friend?

1 个答案:

答案 0 :(得分:1)

如果您学习Many to ManyInserting & Updating Related Models,您会找到其他方法:

这是一个简单的问题解决方法:

 public function store(Request $dados) {
    $friend = Friend::create($dados->all());
    foreach ($dados->wish as $wish) {
        $friend->wishes()->attach($wish);//wishes is the method name that you define in model
    }
    if(is_null($friend)) {
        return redirect()->route("friend.index")->withErrors("Erro ao criar curso. Por favor, tente novamente.");  
    }
    else {
        return redirect()->route("friend.index")->with("Curso inserido com sucesso!");
    }

当您输入多个时,您应该将表单输入更改为数组 name="wish[]"

<div class="form-group">
    <label for="wish" class="control-label">Wishes:</label>
    <select id="wish" name="wish[]" class="form-control" multiple required>
        @foreach($wishes as $wish)
            <option value="<?php echo $wish->id; ?>"><?php echo $wish->name; ?></option>
        @endforeach
    </select>
</div>