gpt4 book ai didi

mysql - 从具有近相关表条件的远相关表中获取 N 行

转载 作者:行者123 更新时间:2023-11-30 22:55:23 24 4
gpt4 key购买 nike

我有两个表,schedulesshifts,是一对多的关系。

scheduledaymonthyear 字段,以及is_published bool 值。 shift 有一个 user_idusers 具有一对一的关系。

现在,我想获取 用户 接下来的 5 个即将到来的 shifts。我必须从 schedule 开始,因为该表中有日期。但是,更重要的是,我应该只检索属于已发布的 scheduleshifts

所以最大的问题是:

条目数应该是5类。但是,从时间表开始,直到有 5 个属于用户的类次,我才知道我需要检索多少个时间表。

除了反复试验(即检索 x 个下一个时间表并测试以查看是否存在足够的类次。如果没有,检索下一个 n 个时间表直到满足配额),是否有其他选择?

时间表架构

Schema::create('schedules', function(Blueprint $table) 
{
$table->increments('id');
$table->integer('user_id', false, true);
$table->integer('client_id', false, true);
$table->datetime('for');
$table->enum('type', array('template', 'revision', 'common'));
$table->string('name', 50)->default('Untitled Template');
$table->boolean('is_published');
$table->timestamp('published_at');
$table->softDeletes();
$table->timestamps();
});

这里,user_id 是创建者的 ID,而不是日程表的所有者。这用于跟踪将来如何创建计划。

转变模式

Schema::create('shifts', function(Blueprint $table) 
{
$table->increments('id');
$table->integer('schedule_id', false, true);
$table->integer('user_id', false, true);
$table->foreign('schedule_id')->references('id')->on('schedules')->onDelete('cascade');
$table->softDeletes();
$table->timestamps();
});

最佳答案

我会走简单的路:

// User model
public function shifts()
{
return $this->hasManyThrough('Shift', 'Schedule');
}

然后:

$now = Carbon\Carbon::now();

$upcomingShifts = $user->shifts()
->where('schedules.is_published', 1)
->where('schedules.for', '>', $now)
->orderBy('schedules.for')
->take(5)
->get();

你可以让它更灵活一点,例如。这样:

// User model
public function getUpcomingShifts($limit = 5)
{
$joinTable = $this->shifts()->getParent()->getTable(); // schedules

$now = Carbon\Carbon::now();

return $this->shifts()
->where($joinTable.'.is_published', 1)
->where($joinTable.'.for', '>', $now)
->orderBy($joinTable.'.for')
->take($limit)
->get();
}

// then
$user->getUpcomingShifts();

关于mysql - 从具有近相关表条件的远相关表中获取 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26619850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com