Laravel:如何使用数据透视表获取记录?

时间:2018-11-25 02:58:46

标签: laravel eloquent laravel-5.1 lumen

我在任务和用户之间有很多关系,我正在尝试获取已存档的任务,已存档的任务是:

  • is_done = 1
  • 的任务
  • 昨天或之前完成的任务,不包括今天完成的任务

  • 用户只能看到他创建或已分配的存档任务 如果用户分配了任务,则其ID将存储在数据透视表中 桌子

  • 出于问题范围之外的原因,我只能使用下面的Task.php中所示的数据透视表来吸引用户。

Task.php模型

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

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

分别为实际表

enter image description here

enter image description here

我的代码:

助手在下面

    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,没有结果,tasks数组为null,尽管我的代码似乎是正确的,并且表包含应返回的1条记录。

1 个答案:

答案 0 :(得分: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();
}