I have this problem: some users (user_id) have access to reports (report_id), but for a limited time only (in days, days_count) for any report, but each report can be accessed only a certain amount of tries (report_count) during the days_count.
In one table, the logic would be this:
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
The first row would be read as: "the user with user_id 5, has access to report_id 1, he has 5 access left, and 7 days left for any access" etc.
I was thinking on make 2 tables like this:
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
Using that logic of 2 tables, how could I use the Laravel relations to establish my, relations?
For something like this you would use a BelongsToMany relationship between User
and Report
where the first table in your example is the pivot table.
I would also suggest changing the days_count
to be a timestamp as you then don't need to update the days_count
at the start/end of each day (assuming that's what you're doing).
Then for getting reports that a User has access to would look something like:
$reports = $user->reports()
->whereDate('access_until', '>=', now())
->where('report_count', '>=', 1)
->get();
You can use the belongsToMany relation with additional pivot fields.
Your User model should have the relation method to reports like this:
/**
* 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');
}
The Report model would then have the following counterpart
/**
* 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');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.