Sql Laravel,最好的联系方式
我有这个问题:一些用户(用户id)可以访问报告(报告id),但是对于任何报告,访问时间都是有限的(以天为单位,天为单位),但是在天为单位,每个报告只能访问一定数量的尝试(报告为单位) 在一个表中,逻辑如下:Sql Laravel,最好的联系方式,sql,laravel,Sql,Laravel,我有这个问题:一些用户(用户id)可以访问报告(报告id),但是对于任何报告,访问时间都是有限的(以天为单位,天为单位),但是在天为单位,每个报告只能访问一定数量的尝试(报告为单位) 在一个表中,逻辑如下: One Table --------- id - user_id - report_id - report_count - days_count 1 - 5 - 1 - 5 - 7 2 - 5 - 2 - 3 - 7 3 - 3 - 1 - 4 - 10 第一行将被理解为:“用户id为5的
One Table
---------
id - user_id - report_id - report_count - days_count
1 - 5 - 1 - 5 - 7
2 - 5 - 2 - 3 - 7
3 - 3 - 1 - 4 - 10
第一行将被理解为:“用户id为5的用户有权访问报告id 1,他还有5个访问权限,还有7天可以访问”
等等
我想做两张这样的桌子:
Table 1
---------
id - user_id - report_id - report_count
1 - 5 - 1 - 5
2 - 5 - 2 - 3
3 - 3 - 1 - 4
Table 2
---------
id - user_id - days_count
1 - 5 - 7
2 - 2 - 10
/**
* User belongs to many (many-to-many) Reports.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function reports()
{
// belongsToMany(RelatedModel, pivotTable, thisKeyOnPivot = report_id, otherKeyOnPivot = user_id)
return $this->belongsToMany(Report::class)->withPivot('report_count', 'days_count');
}
使用两个表的逻辑,我如何使用Laravel关系来建立我的关系?您可以将与其他透视字段一起使用。您的用户模型应具有以下报告的关联方法:
Table 1
---------
id - user_id - report_id - report_count
1 - 5 - 1 - 5
2 - 5 - 2 - 3
3 - 3 - 1 - 4
Table 2
---------
id - user_id - days_count
1 - 5 - 7
2 - 2 - 10
/**
* User belongs to many (many-to-many) Reports.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function reports()
{
// belongsToMany(RelatedModel, pivotTable, thisKeyOnPivot = report_id, otherKeyOnPivot = user_id)
return $this->belongsToMany(Report::class)->withPivot('report_count', 'days_count');
}
然后,报告模型将具有以下对应项
/**
* Report belongs to many (many-to-many) Users.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
// belongsToMany(RelatedModel, pivotTable, thisKeyOnPivot = user_id, otherKeyOnPivot = report_id)
return $this->belongsToMany(User::class)->withPivot('report_count', 'days_count');
}
对于这种情况,您可以使用
User
和Report
之间的关系,其中示例中的第一个表是透视表
我还建议将days\u count
更改为时间戳,因为这样您就不需要在每天的开始/结束时更新days\u count
(假设您正在这样做)
然后,对于获取用户有权访问的报告,如下所示:
$reports=$user->reports()
->whereDate('access_until','>=',now())
->其中('report_count','>=',1)
->get();
您的时间戳是对的。在前面,管理员将输入天数,但表格必须是时间戳。您可以简单地计算管理员输入天数时的时间戳,例如now()->addDays($request->input('days'))
和pivot('report\u count',days\u count'))
这些是我的示例表1和表2?这两个答案都帮了我很大的忙,耶稣。这是你第一个例子“一张表”中的附加字段,嗯,我明白了。因此,我必须只使用一个表(“一个表”),一个透视表,而不使用我在示例中输入的“id”字段。然后我可以访问与您的关系答案,并获得用户的报告,正如Ross Wilson在另一个答案中提到的那样。完全正确。您将只有透视表。您可以通过$report->pivot->report\u count编码>或通过$user->reports()->wherePivot('report\u count',1)查询它们
我认为,days\u count
应该被一个datetime列替换,该列包含用户无法访问报告的日期时间。如果没有在
列(或类似列)创建的,您当前的数据库设计将无法正常工作,因为天数不会每天更新最好的设计可能是您的一个表设计(以及我建议的更改)和另一个记录用户访问报告(即用户何时访问哪个报告)的表,因为它为您提供了最多的信息,并允许您非常轻松地计算状态。