Laravel Database structure 'apply' - mysql

So I have a weird question.
I'm making an application in Laravel and Angular. I'm using Eloquent models.
Right now I have 2 tables, 1 users table (with the users info), and 1 events table (with the name, date, ... of an event).
These 2 are binded by a oneToMany relation (Every event belongs to an user). But now I would like people to sign up for that event. ( a switch in the front end, so they can apply for the event).
So, many users will have many events.
The catch is also, the owner of the event can manually set an maximum # users. (This is an tinyINt in my event table).
So now my question. How can I pull this off?
Options I have thought off:
1. I make a pivot table
-> Is this possible? Because the User and the event are already binded by a one to many realtion? So how can I bind them with a many to many relation again?
2. Every time a user signs op, I add his ID to an array in the events table.
-> Is this possible? I could then be able to set the maximum # users by checking the length of the array?
Thank you friends!

Using a pivot table is the correct approach here. The fact that the two tables are already bound by a different relation should not deter you.
class Events extends Eloquent
{
public function owner()
{
return $this->belongsTo(App\User::class);
}
public function subscribers()
{
return $this->belongsToMany(App\User::class, 'event_user');
}
public function canAddSubscriber()
{
if ( ! $this->max_users) return true;
return $this->max_users < $this->subscribers()->count();
}
}
As you can see, you can use the relationship to determine if a subscriber can still be added.

Related

Laravel Eloquent - auto-numbering on has many relationship

I'm very much a beginner when it comes to database relationships hence what I suspect is a basic question! I have two database tables as follows:
Projects
id
company_id
name
etc...
rfis
id
project_id (foreign key is id on the Projects table above)
Number (this is the column I need help with - more below)
question
The relationships at the Model level for these tables are as follows:
Project
public function rfi()
{
return $this->hasMany('App\Rfi');
}
RFI
public function project()
{
return $this->belongsTo('App\Project');
}
What I'm trying to achieve
In the RFI table I need a system generated number or essentially a count of RFI's. Where I'm finding the difficulty is that I need the RFI number/count to start again for each project. To clarify, please see the RFI table below which I have manually created with the the 'number' how I would like it displayed (notice it resets for each new project and the count starts from there).
Any assistance would be much appreciated!
Todd
So the number field depends on the number of project_id in the RFI table. It is exactly the number of rows with project_id plus one.
So when you want to insert a new row, you calculate number based on project_id and assign it.
RFI::create([
'project_id' => $project_id,
'number' => RFI::where('project_id', $project_id)->count() + 1,
...
]);
What I understood is that you want to set the value of the "number" field to "1" if it's a new project and "increment" if it's an existing project. And you want to automate this without checking for it every time you save a new row for "RFI" table.
What you need is a mutator. It's basically a method that you will write inside the desired Model class and there you will write your own logic for saving data. Laravel will run that function automatically every time you save something. Here you will learn more about mutators.
Use this method inside the "RFI" model class.
public function setNumberAttribute($value)
{
if(this is new project)
$this->attributes['number'] = 1;
else
$this->attributes['number']++;
}
Bonus topic: while talking about mutators, there's also another type of method called accessor. It does the same thing as mutators do, but just the opposite. Mutators get called while saving data, accessors get called while fetching data.

Laravel: How to get counter value when inserting with UUID and Auto Increment

My models have both id and counter attributes. The id is a UUID, and the counter is an integer which is auto-incremented by the database.
Both are unique however I rely on id as the primary key. The counter is just a human-friendly name that I sometimes display to the user.
Immediately before an object is created a listener gives it a UUID. This works fine.
When the record is saved, MySQL increments the counter field. This works fine except that the copy of the object which I have in memory does not have the counter value. I can reload the object to find out what its counter is, but that would require another database query.
Is there a way to find the value of the counter without a specific database query? For example, is it returned as part of the response from the database when a record is created?
Few things:
Use create(array $attributes) and you'll get exactly what you want. For this having right, you have to ensure that $fillable array consists all attributes' names passed to create method.
You should use Observer on model instead of listener (most likely creating method).
Personal preference using Eloquent is that you should use id for id (increment field) and forget custom settings between models because by default it is what relations expect and so on
public function secondModels()
{
return $this->hasMany(SecondModel::class);
}
is pretty much no brainer. But for having this working best way would be (also following recommendations of this guy) FirstModel::id, SecondModel::id, SecondModel::first_model_id; first_models, second_models as table names. Avoiding and/or skipping this kind of unification is lot of custom job afterward. I don't say it can't be done but it is lot of non-first-time-successful work done.
Also, if you want visitor to get something other than id field name, you can make computed field with accessor:
/**
* Get the user's counter.
*
* #return string
*/
public function getCounterAttribute(): string
{
return (string)$this->id;
}
Which you call then with $user->counter.
Also personal preference of mine is to have most possible descriptive variable names so uuid field of mine would be something like
$table->uuid('uuid4');
This is some good and easy to make practice of Eloquent use.
Saying all this let me just to say that create() and save() will return created object from database while insert() shall not do it.

dynamic value in one field in mysql DB

I use laravel framework . I have two table. users and points . that has one to many relationship between them.in points table saved many records related to a one user that keep all of the ponits we assign to this user.I want to keep sum this points to one field as sumpoints filed in user table.how can i do it in laravel
Do something like this in your Points model:
public static function boot()
{
parent::boot();
self::created(function($model){
$user = Auth::user();
$user->sumfields = Points::where('user_id',$user->id)->sum('points');
$user->save();
});
}
The self::created function gets called after a new instance of that model has been created.
However if this was my project, I would probably do what Ivan Jelev suggested to you (doing the sum only when you need it).

how to track changes of relation between two models in yii2

I have two models with a simple 1-n relation (category and item with category_id). I would like to show how much items there is in the category. I would like to have the number cached rather then always doing the count, so I have an extra field in category table called "total_items_count".
How to best do this total count triggering, when to call the "countUpdate" function since the relation could change from several places (backend, api, frontend...).
My initial plan was to use AFTER_UPDATE event, but "link()" must be called after the item is stored in database (on adding new item at least) so then I do not know which category is the item related to. I also need to know the old category, in case item goes from one category to another. In the backend controller I am using $item->link('category', $categoryObj); as I might change this relation to n-n someday.
Any advice on how to have complete control if the link between item and category changes and then update the count for the old and new linked category?
Thanks
The first and most important thing you need to now, is that you need to update the category count field via the ActiveRecord::updateCounters() method, in order to prevent incorrect update from multiple places. So you can do one of those things:
In the category item model you can do the following:
public function save($runValidation = true, $attributeNames = null)
{
if (parent::save(runValidation, attributeNames)) {
$this->category->updateCounters(['total_items_count' => 1]);
return true;
}
return false;
}
Or you can write a centralized component (let's say app\components\Category) which you will call from the whole application. This component will have a method that saves an item. For example:
public function saveItem($category, $item)
{
if ($item->save()) {
$item->link('category', $category);
$category->updateCounters(['total_items_count' => 1]);
return true;
}
return false;
}
Of course, when you delete an item, you will call:
$category->updateCounters(['total_items_count' => -1]);
See the ActiveRecord::updateCounters() API
From the Yii2 documentation:
Note: If you use yii\db\ActiveRecord::save() to update a counter column, you may end up with inaccurate result, because it is likely the same counter is being saved by multiple requests which read and write the same counter value.
If you need to keep track of which is the old category, just create another column let's say "old_category" to the category item table and when you change the category of the item put the old category id there, and the new category id to the category_id column.
Does that helps? If you have any questions, please ask!

MySQL database structure advice needed. Two many-to-many from one table to two other that are in one-to-many relation

I have this setup as my database structure which already works pretty well, but I feel like it could be better, but cannot figure out how.
Database Structure:-
Events can have multiple sub-events. Users can join these events and optionally their sub-events. With this structure I have all constraints, but the one that links the event attending with the sub event attendings => there can be sub event attendings left without having the main event attending (this shouldn't be possible as users who don't attend the main event cannot attend it's sub events).
I am currently working with Laravel so it looks like this:
User:
hasMany Event (as organizer of these events)
belongsToMany EventAttending (which events is a user joining)
belongsToMany SubEventAttending (which sub-events is a user joining)
Event:
belongsTo User
hasMany SubEvent
belongsToMany EventAttending (which users are attending this event)
SubEvent:
belongsTo Event
belongsToMany SubEventAttending (which users are attending this sub-event)
The problem arises when trying to manage the sub-event attendings of a user. How would I make this constraint between the event and sub-event attendings exist, while keeping it clean with the capabilities of Laravel / What can you give as advice for a better structuring / How would you guys do it?
Edit
To clarify, the events and sub-events store different things, have different properties. Also I need to store information for the event attendings (like did he attend in real life) and sub-event attendings, most likely differing ones.
Edit
Edward Haber has the better structure, but as my two pivot tables (the connection between User-Event and User-SubEvent) store additional diferent type of information, currently chose to remain with the initial design.
One of the biggest problems I am facing (which does exist with both structure) is querying for a User while getting the attended Events with the attended SubEvents. Trying to achive this result:
User[]:{
...,
attending_events[]:{
...,
attending_sub_events[]:{
...
}
}
}
Been thinking for hours for a clean solution, couldn't get anything else to work. Wouldn't like to write the whole SQL query manually. My current implementation with the two pivot table looks like this (result not nested, code messy):
$users = User::withCount(['attendingEvents' => function($query) use($eventId){
$query->where('event_id', $eventId);
}])
->with(['attendingSubEvents' => function($query) use($eventId){
$query->select('id')->whereHas('event', function($query) use($eventId){
$query->where('id', $eventId);
});
}]);
With this approach I get the sub-events separated from the main event. (querying only for the main attending-event count, because I only need to determine whether he is joining or not).
The pattern for this type of solution is to use a Polymorphic Relationship. This solution focuses just on connecting the User to the Event and SubEvent - the rest of the relations look correct.
<?php
class User extends Model {
public function attending() {
return $this->morphTo();
}
}
<?php
class Event extends Model {
public function attendees() {
return $this->morphMany('App\User', 'attending')
}
}
<?php
class Subevent extends Model {
public function attendees() {
return $this->morphMany('App\User', 'attending')
}
}
The users table needs these fields:
*users*
-----
id
attending_id
attending_type
This is all untested - but the basic idea. (Edited: changed name of polymorphic method to attending from attendee)