Laravel:如何从中间表获取记录?

24 浏览
0 Comments

Laravel:如何从中间表获取记录?

我正在使用Lumen 5.1版本,我在任务和用户之间有一个多对多的关系。

任务模型

public function user()
{
    return $this->belongsToMany('App\Models\Auth\User', 'task_user');
}
public function domain()
{
    return $this->hasOne('App\Models\Domain', 'domain_id');
}

用户模型

public function tasks()
{
    return $this->belongsToMany(Task::class, 'task_user');
}

UserTask模型

class UserTask {}

我想要查询任务的用户,我的代码是

$tasks = Task::Where(function ($query) use ($domainId) {
    $query->where("domain_id", $domainId)
        ->where("is_done", 0)
        ->orwherehas('tasks.user.id', \Auth::id)
        ->orderBy('due_date', 'DESC');
})
->orWhere(function ($query) use ($domainId) {
    $query->where("domain_id", $domainId)
        ->Where("is_done", 1)
        ->Where("closed_dated", Carbon::today())
        ->orwherehas('tasks.user.id', \Auth::id)
        ->orderBy('closed_date', 'ASC');
})
->get();

我的问题是whereHas是否正确?tasks.user.id是否正确?我可以通过这种方式获取用户的id吗?因为这个问题我这样做的。

技术主管告诉我我的代码是错误的,他会使用where,他说当你想要运行一个闭包时才使用whereHas

迁移:

任务表

public function up()
{
    Schema::create($this->getTable(), function (Blueprint $table) {
        $table->increments('id');
        $table->string('title')->nullable();
        $table->dateTime('submit_date');
        $table->dateTime('closed_date');
        $table->dateTime('due_date');
        $table->tinyInteger('is_done')->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());
}

任务用户表

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');
    });
}
public function down()
{
    Schema::drop($this->getTable());
}

0
0 Comments

问题:如何从一个关联表中获取记录?

原因:原始代码中使用了错误的查询方法,并且有一些语法错误。

解决方法:

1. 在whereHas方法的第二个参数中使用闭包(匿名函数),并将Auth::id更正为Auth::id()

2. 可以选择使用auth()助手函数来代替Auth门面(Facade)。

以下是正确的代码解决方法:

$tasks = Task::where("domain_id", $domainId)
    ->where(function ($query) use ($domainId) {
        $query
            ->where("is_done", 0)
            ->whereHas('user', function ($query) {
                $query->where('id', auth()->id());
            });
    })
    ->orWhere(function ($query) use ($domainId) {
        $query
            ->where("is_done", 1)
            ->where('closed_by', auth()->id())
            ->whereDate("closed_dated", '>=', Carbon::today()->startOfDay());
    })
    ->orderBy('due_date', 'DESC')
    ->orderBy('closed_date', 'ASC')
    ->get();

0
0 Comments

Laravel: 如何从中间表获取记录?

在Laravel中,有一个名为“任务列表”的应用程序。下面的内容是关于如何在Laravel中获取记录的。

首先,我们需要获取当前用户的任务。我们可以使用`Auth::user()->tasks()->where('is_done',0)->get();`语句来实现。这将返回当前用户的所有未完成任务。

接下来,我们想要获取与用户相关的任务。我们可以使用`Tasks::with(['user'])->where('is_done',1)->get();`语句来实现。这将返回所有已完成的任务,并且与用户相关联。

对于已认证的用户,我们可以使用以下代码来获取任务:

Auth::user()->tasks()
    ->where('domain_id', $domainId)
    ->where(function ($query) {
        $query->where('is_done', 1)
              ->orWhere(function($query) {
                 $query->where('is_done', 0)
                       ->where('closed_dated', Carbon::today())
            });
        });
    })
    ->get();

以上代码将返回已认证用户在指定领域中的所有任务,包括已完成和未完成的任务。

有人问道如何从用户中获取任务的id,答案是`task.user.id`。

还有人提出了一个问题,他只想获取已授权用户的所有任务,而不是所有用户的任务。我们可以对代码进行修改,将`Auth:user()->tasks()->where('is_done',1)->orWhere('closed_dated', Carbon::today())`这一行修改为`Auth:user()->tasks()->where('is_done',1)->where('domain_id', $domainId)->orWhere('closed_dated', Carbon::today())`。这样就可以只获取已授权用户的任务了。

最后,有人提出了另一个问题,他想知道是否可以嵌套查询。虽然我从来没有写过这样的嵌套查询,但我认为是可能的。

有趣的是,有人表示对此不太确定,但会在晚上尝试一下并告诉我结果。

0