Multi-select dropdown with Many to many relation

萝らか妹 提交于 2020-06-17 09:10:49

问题


In my laravel project I created three tables as employees, teams and employee_teams. There is many to many relationship in "employee_teams" tables, with the foreign keys of employee_id and team_id.

"employee_teams" table DB structure

id | employee_id | team_id

In the Employee form there is a multi-select dropdown which helps to assign multiple teams for the particular employee.

<select name="namedropdown[]" id="namedropdown" class="selectpicker" multiple data-live-search="true">
    <option value="" disabled selected>Nothing selected</option>
         @foreach ($tdropdown as $key => $tdrop)
         <option value="{{$key}}">{{$tdrop}}</option>
         @endforeach
</select>

What I want is to save "team_id" and "employee_id", to the "employee_teams" table.

Here is employee model

class employee extends Model
{  
    public function teams()
    {
         return $this->belongsToMany(team::class, 'employee_teams');
    }
}

Here is team model

class team extends Model
{
    public function employees()
    {
         return $this->belongsToMany(employee::class, 'employee_teams');
    }
}

Here is employee_team table migration

class CreateEmployeeTeamsTable extends Migration
{
    public function up()
    {
        Schema::create('employee_teams', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('employee_id')->unsigned();
            $table->integer('team_id')->unsigned();
            $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
            $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
            $table->timestamps();
        });
    }

Here is store function in employee controller

use App\employee;
use App\team;
use App\employee_team;

// codes

 $employee = new employee();

       $employee->namedropdown = implode(',', $request->input('namedropdown')); //Already save multi-select dropdown ids to the database 

       $employee->save();

 $employee_team = new employee_team();

      $employee->teams()->attach($employee->namedropdown);

      return redirect()->route('employee.index')->with('success','Data Added');
}

Error comes as SQLSTATE[01000]: Warning: 1265 Data truncated for column 'team_id' at row 1

Please help me to save employee_id and team_id to the "employee_teams" table. Thank you so much.


回答1:


A working sample (tested):

Migration: 2020_06_16_000000_create_employees_table.php

class CreateEmployeesTable extends Migration
{

    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Migration: 2020_06_16_000000_create_teams_table.php

class CreateTeamsTable extends Migration
{
    public function up()
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('teams');
    }
}

Migration: 2020_06_16_000000_create_employee_team_table.php

class CreateEmployeeTeamTable extends Migration
{
    public function up()
    {
        Schema::create('employee_team', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('employee_id')->nullable();
            $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
            $table->unsignedBigInteger('team_id')->nullable();
            $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('employee_team');
    }
}

Model: Employee.php

class Employee extends Model
{    
    public function teams()
    {
        return $this->belongsToMany('App\Team');
    }
}

Model: Team.php

class Team extends Model
{    
    public function employees()
    {
        return $this->belongsToMany('App\Employee');
    }
}

Routes: routes/web.php:

Route::get('/select_team/{id?}', 'EmployeeController@select_team')->name('employee.select_team');
Route::post('/save_teams/{id?}', 'EmployeeController@save_teams')->name('employee.save_teams');

Controller: EmployeeController.php

use Illuminate\Http\Request;
use App\Team;
use App\Employee;

class EmployeeController extends Controller
{
    public function select_team($employee_id){    
        return view('select_team', ['tdropdown'=>Team::all(), 'employee'=>Employee::find($employee_id)]);
    }

    public function save_teams(Request $request, $employee_id){   
        $employee = Employee::find($employee_id);
        foreach ($request->namedropdown as $team_id){
            $employee->teams()->attach($team_id);
        }

        return redirect()->route('employee.index')->with('success','Data Added');
    }
}

Blade: select_team.blade.php

<!DOCTYPE html>
<form action="/save_teams/{{$employee->id}}" method="post">
        @csrf
    <select name="namedropdown[]" id="namedropdown" class="selectpicker" multiple data-live-search="true">
    <option value="" disabled selected>Nothing selected</option>
            @foreach ($tdropdown as $tdrop)
            <option value="{{$tdrop->id}}">{{$tdrop->name}}</option>
            @endforeach
    </select>
    <button>Submit</button>
</form>
</html>

I think it's a good example that can give you an idea.



来源:https://stackoverflow.com/questions/62410546/multi-select-dropdown-with-many-to-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!