简体   繁体   English

Laravel 多对多存储到数据库

[英]Laravel Many to many store to database

I want a system where I connect users with tasks and later I can assign tasks to different users from the amdin panel.我想要一个系统,我可以将用户与任务连接起来,然后我可以从 amdin 面板将任务分配给不同的用户。 My program doesn't work, it doesn't assign tasks to users.我的程序不起作用,它不向用户分配任务。 Later, I want to make sure that when a user logs in, they can only see their own tasks that an amdin has given them.后来,我想确保当用户登录时,他们只能看到 amdin 给他们自己的任务。 Please help me what is the problem?!请帮我看看是什么问题?!

Create 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();
        
        });

Create users创建用户

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();
        });

Create tasks创建任务

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

Task model任务模型

<?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');
    }
 
}

User model用户模型

<?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();        
    }

}


Task controller (here i want to upload tasks)任务控制器(这里我想上传任务)

<?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');
    }
}

And after i run my upload form, on the phpmyadmin the task has uploaded done but in the user_task table not working.在我运行上传表单后,在 phpmyadmin 上,任务已上传完成,但在 user_task 表中不起作用。 Because its not working i cant display tasks for the users.因为它不起作用,我无法为用户显示任务。 Thank you for your replies!谢谢您的回复!

You can use attach(), detach() or sync() functions in controller.您可以在控制器中使用 attach()、detach() 或 sync() 函数。

For example:例如:

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.
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM