同一模型的 Laravel 一对多和多对多

问题描述

我正在尝试制作一个任务管理系统。用户可以创建一个任务并将多个用户分配给该任务。所以任务表会有一个 user_id 来标识创建任务的用户。有一个包含 user_id 和 task_id 的数据透视表,以便可以将任务的受让人映射到那里。

任务表详细信息

Schema::create('tasks',function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('content');
        $table->Integer('views');
        $table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
        $table->timestamps();
    });

用户表结构

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

数据透视表 task_user 结构

Schema::create('task_user',function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->foreignId('task_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
        $table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
        $table->string('status')->default('Todo');
        $table->timestamps();
    });

任务模型有这个

public function users()
{
    return $this->belongsToMany('App\User');
}

用户模型有这个

public function tasks()
{
    return $this->belongsToMany('App\Task');
}

现在我有一个从 UserResource 获取数据的任务资源,但我只能从数据透视表中获取数据。

return [
        'id' => $this->id,'title' => $this->title,'content' => $this->content,'views' => $this->views,'user' => UserResource::collection($this->whenLoaded('users')),'comments' => CommentResource::collection($this->whenLoaded('comments')),'assingnees' => $this->whenPivotLoaded('users',function () {
            return $this->users->pluck('pivot.user_id')->unique()->all();
        }),'created_at' => $this->created_at,'updated_at' => $this->updated_at,];

我想要 assignees 中数据透视表中的用户详细信息和 user 中任务表中的用户详细信息。但最终,我最终在 user 中获得了数据透视表用户,并且在 JSON 响应中没有获得 assignees 变量。如何在单独的变量中获取两个用户数据?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...