Laravel: 如何使用枢轴table获取记录?

Laravel: How to get records by using the pivot table?

我在任务和用户之间有多对多关系,我正在尝试获取存档任务,一个存档任务是:

Task.php 型号

public function taskUsers()
{
    return $this->hasMany('App\Models\Tasks\UserTask')->where('role',1);
}

用户Task.php 模型什么都没有,一个空模型

class UserTask extends BaseModel { }

迁移

class CreateTasksTable extends Migration
{
    protected $table = 'tasks';
    protected $app_table = true;


    public function up()
    {
        Schema::create($this->getTable(), function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->dateTime('submit_date');
            $table->dateTime('closed_date')->nullable();
            $table->dateTime('due_date')->nullable();
            $table->tinyInteger('is_done')->nullable()->default(0);
            $table->integer('domain_id')->unsigned()->nullable();
            $table->foreign('domain_id')->references('id')
                ->on(self::getTableName('domains'))->onDelete('cascade');
            $table->bigInteger('created_by')->unsigned()->nullable();
            $table->foreign('created_by')->references('id')
                ->on(self::getTableName('auth_users', false))->onDelete('cascade');
            $table->bigInteger('closed_by')->unsigned()->nullable();
            $table->foreign('closed_by')->references('id')
                ->on(self::getTableName('auth_users', false))->onDelete('cascade');
            $table->timestamps();
        });

    }
    public function down()
    {
        Schema::drop($this->getTable());
    }
}

class CreateTaskUsersTable extends Migration
{
    protected $table = 'task_user';
    protected $app_table = true;
    public function up()
    {
        Schema::create($this->getTable(), function (Blueprint $table) {
            $table->increments('id');
            $table->integer('task_id')->unsigned()->nullable();
            $table->foreign('task_id')->references('id')
                ->on(self::getTableName('tasks'))
                ->onDelete('cascade');
            $table->bigInteger('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')
                ->on(self::getTableName('auth_users', false))
                ->onDelete('cascade');
            $table->integer('role');
        });
    }
    public function down()
    {
        Schema::drop($this->getTable());
    }
}

实际分别为table

我的代码:

帮手在下方

    public static function getArchived($domainId, $userId)
    {
        Task::where("domain_id", $domainId)
            ->where("is_done", 1)
            ->where("closed_date", '<', Carbon::today()->startOfDay())

            ->where(function ($query) use ($userId) {
                $query->whereHas('taskUsers', function ($query) use ($userId) {
                    $query->where('user_id', $userId);
                });
            })
            ->orWhere(function ($query) use ($userId) {
                $query->where('created_by', $userId);
            })
->get();
    }

行动:

public function execute()
{
    $domainId = $this->request->get('domain_id');
    $userId = \Auth::id();
    $tasks = TasksHelper::getArchived($domainId,$userId);
    return $this->response->statusOk(['tasks' => $tasks]);
}

我只是得到一个状态 OK,没有结果,任务数组为空,尽管我的代码似乎是正确的并且 tables 包含 1 条应该返回的记录。

您在 getArchived 方法中缺少 return 语句。此外, orWhere 条件似乎不合适。如果您还需要应用前三个条件,则必须使用 parameter grouping。否则查询读取 (1 && 2 && 3 && 4) || 5 而你需要 1 && 2 && 3 && (4 || 5).

public static function getArchived($domainId, $userId)
{
    return Task::where("domain_id", $domainId)
        ->where("is_done", 1)
        ->where("closed_date", '<', Carbon::today()->startOfDay())

        ->where(function ($query) use ($userId) {
            $query->whereHas('taskUsers', function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })->orWhere('created_by', $userId);
        })->get();
}