Laravel 多对多存储到数据库

Laravel Many to many store to database

我想要一个将用户与任务联系起来的系统,稍后我可以从 amdin 面板将任务分配给不同的用户。我的程序不工作,它不向用户分配任务。后来,我想确保当用户登录时,他们只能看到 amdin 给他们的自己的任务。请帮我看看这是什么问题?!

创建user_task

Schema::create('user_task', function (Blueprint $table) {

            $table->id();
            $table->foreignId('task_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamps();
        
        });

创建用户

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('avatar')->default('default.jpg');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

创建任务

Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('alkalmazott');
            $table->string('projekt')->default('-');
            $table->string('feladat');
            $table->date('hatarido');
            $table->timestamps();
        });

任务模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;
    protected $fillable = [
        'alkalmazott', 'projekt' , 'feladat', 'hatarido'
    ];
   
    public function projects(){
        return $this->belongsToMany('App\Models\Project');
    }
    public function users()
    {
    return $this->belongsToMany('User', 'user_tasks');
    }
 
}

用户模型

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use Tasks;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    //public function setPasswordAttribute($password) {
      //  $this->attributes['password'] = Hash::make($password);
    //}

    public function jogoks(){
        return $this->belongsToMany('App\Models\Jogok');
    }
   
   
    public function tasks()
{
  return $this->belongsToMany('Task', 'user_tasks');
}
        /* Check if the user has a role
        * @param string $role
        * @return bool
        */
    public function hasAnyRole(string $role){
        return null !== $this->jogoks()->where('name', $role)->first();        
    }
    /* Check if the user has any given role
        * @param array $role
        * @return bool
        */
    public function hasAnyRoles(array $role){
        return null !== $this->jogoks()->whereIn('name', $role)->first();        
    }

}


任务控制器(这里我要上传任务)

<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;

class TasksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tasks = Task::latest()->paginate(10);
    
        return view('admin.tasks.index',compact('tasks'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.tasks.create', ['users' => User::all()], ['tasks' => Task::all()]);
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'alkalmazott' => 'required',
            'projekt' => 'required',
            'feladat' => 'required',
            'hatarido' => 'required',
            
        ]);
        
       Task::create($request->all());
 

        return redirect()->route('admin.tasks.index')
                        ->with('success','Product created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Task  $Task
     * @return \Illuminate\Http\Response
     */
    public function show(Task $Task)
    {
        return view('admin.tasks.show',compact('Task'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Task  $Task
     * @return \Illuminate\Http\Response
     */
    public function edit(Task $Task)
    {
        return view('admin.tasks.edit',compact('Task'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Task  $Task
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Task $Task)
    {
        $request->validate([
            'alkalmazott' => 'required',
            'projekt' => 'required',
            'feladat' => 'required',
            'hatarido' => 'required',
        ]);
        
        $Task->update($request->all());
        
        return redirect()->route('admin.tasks.index')
                        ->with('success','Product updated successfully');
                    
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Task  $Task
     * @return \Illuminate\Http\Response
     */
    public function destroy(Task $Task)
    {
        $Task->delete();
    
        return redirect()->route('admin.tasks.index')
                        ->with('success','Product deleted successfully');
    }
}

在我 运行 我的上传表单之后,在 phpmyadmin 上任务已经上传完成但在 user_task table 中不工作。因为它不起作用,我无法为用户显示任务。感谢您的回复!

您可以在控制器中使用 attach()、detach() 或 sync() 函数。

例如:

public function store(Request $request){
    // ...

    $task = Task::create($request->all());
    $task->users->attach($request->users); // or you can use sync(), according to your needs and project
    // $request->users must be an array like [1,3,10,21,28] etc.
    // ...
}