在不创建

时间:2018-03-07 21:09:50

标签: laravel one-to-many

我只是有一点问题。我有一对多的关系。一个团队有很多用户。许多用户都有一个团队。 我有六个团队,用户必须选择一个团队。如何在不在数据库“团队”中创建新条目的情况下将团队与用户连接?

用户:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->string('name');
        $table->integer('team_id')->unsigned()->nullable();
        $table->foreign('team_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('username')->nullable()->unique();
        $table->string('email')->unique();
        $table->string('phone')->nullable()->unique();
        $table->string('avatar');
        $table->string('slug');
        $table->string('password');
        $table->date('birthday');
        $table->boolean('gender');
        $table->rememberToken();
        $table->timestamps();
    });
}

小组:

public function up()
{
    Schema::create('teams', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->string('name');
        $table->string('image');
        $table->string('image_thumbnail');
        $table->timestamps();
    });
}

控制器:

    public function storeTeam($request)
{
    $user = Auth::user();
    $team = Team::findOrFail($request->team_id);
    $user->team()->associate($team);

    return redirect()->back()->with('success', lang::get('messages.team'));
}

查看:

<div class="col-md-12">
<form method="POST" action="{{ URL::route('store.team') }}">
      {{ csrf_field() }}
    <ul class="row clients-dotted list-inline text-center">
      @foreach ($teams as $team)
      <li class="col-md-4 col-sm-3 col-6">
        <div class="cc-selector">
          <input id="team{{$team->id}}" type="radio" name="team" value="{{$team->id}}" />
          <label style="background-image:url({{ $team->image_thumbnail }});" class="team-cc" for="team{{$team->id}}"></label>
          <p>{{$team->name}}</p>
        </div>
      </li>
      @endforeach
    </ul>
  <button type="submit" class="mb-50 float-right mr-20 btn btn-shadow-1 btn-primary">weiter</button>
</form>

路线:

Route::post('/welcome/team', 'ProfilesController@storeTeam')->name('store.team');

我有一点问题并得到错误: 输入错误:

Type error: Too few arguments to function App\Http\Controllers\ProfilesController::storeTeam(), 0 passed and exactly 1 expected

1 个答案:

答案 0 :(得分:1)

假设您将team_id存储在user model上,您可以使用associate方法设置孩子的主键 - user情况下

$user->team()->associate($team);

您可以将选定的team传递给控制器​​。不管怎么样。您可以将其作为路线的一部分传递,也可以从表单中传递团队ID并从request获取。

您期望将变量传递给名为$request的控制器。你想要的是注入$request作为依赖。你可以通过输入解析变量来做到这一点:

public function storeTeam(Request $request)

请注意,您需要在文件顶部放置use Illuminate\Http\Request;,否则您将收到有关Request课程的错误。