Laravel 多对多存储到数据库

Posted

技术标签:

【中文标题】Laravel 多对多存储到数据库【英文标题】:Laravel Many to many store to database 【发布时间】:2021-12-02 01:25:31 【问题描述】:

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

创建用户任务

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 表中不起作用。因为它不起作用,我无法为用户显示任务。感谢您的回复!

【问题讨论】:

【参考方案1】:

您可以在控制器中使用 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.
    // ...

【讨论】:

我把这个$task-&gt;users()-&gt;sync($request-&gt;users);同步我认为这对我来说更好,但问题是一样的......找不到类'用户' 好的,我使用了同步,我发现模型上的问题 -> 我将 return $this-&gt;belongsToMany('User', 'user_task'); 更改为 return $this-&gt;belongsToMany(User:class, 'user_task'); 在任务模型中也是如此......但问题没有解决。现在商店功能正在工作,但我在 user_task 表中看不到任何内容......所以它是空的 它不起作用,而且它确实表明我使用同步或附加:( 我可以在 github 或任何其他平台上查看您的所有项目以及您的所有代码,我想帮助您

以上是关于Laravel 多对多存储到数据库的主要内容,如果未能解决你的问题,请参考以下文章

Laravel - 将数据保存到多对多关系

在 laravel 中使用多对多关系同步:PostgreSQL 数据透视表不更新

与同一张表的关系(多对多?) - Laravel

在多对多关系 laravel4 的情况下更新数据透视表

Laravel 多对多合并 Pivot?

Laravel 多对多关系( hasMany 或 belongsToMany )