【发布时间】:2014-12-24 12:54:03
【问题描述】:
我有两张表,schedules 和shifts,是一对多的关系。
schedule 具有 day、month、year 字段以及 is_published 布尔值。 shift 有一个 user_id 与 users 建立一对一的关系。
现在,我想获得 user 中的下 5 个即将到来的 shifts。我必须从schedule 开始,因为该表中有日期。但是,更重要的是,我应该只检索属于已发布schedule 的shifts。
所以最大的问题是:
条目数应为 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,而不是日程所属的人。这用于跟踪将来如何创建计划。
Shift 架构
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();
});
【问题讨论】:
-
您是否在 Eloquent 模型中设置了关系?
-
是的,关系是在 Eloquent 表中设置的。我的问题不是如何链接关系,而是如何获取一定数量的
shifts,而是从schedule开始 -
我明白了,只是在确保...但是我还有一个问题。您写道
shifts与users具有一对一的关系。另一方面,您说您想要属于用户的即将到来的 5 个班次。你真的想要最后的结果中的时间表吗? -
@lukasgeiter,感谢您的回复。不,我不想在最后安排日程。我想得到一个
shifts的数组。我希望用户能够看到他们即将到来的 5 班次;这些转变可能发生在下周,或者 5 次可能跨越下个月或下一年。我从schedule开始的原因是因为schedule中有日期条目。shift只是通过它的 id 引用schedule。 -
1 为什么你对日期使用这种奇怪的模式而不是时间戳? 2 你期望的结果是什么?
标签: mysql laravel laravel-4 eloquent