I've been having this question for quite a long time. I guess it's more of a design problem. So I need to create a User with a mentor role that has many tutorships, but in the create user view I want to be able to add as many tutorships as I want. Once the tutorships are created, I want to be able to perform CRUD operations on them.
However, I want to be able to do this before actually saving its parent model (User) in the database. What is the common approach here? Am I supposed to create and then persist each Tutorship with an empty foreign key until I save the user? Or is it better if all the Tutorships are "floating around" until I save my user?
I worked through this earlier. I had created a trait I used on my models to allow setting relations and then I had to override the save and push on the model to work properly.
Set hasOne relation to new instance of child model
Related
I have 4 tables. Two of them are monomorphic and two of them are polymorphic.
Monomorphic:
Templates, Modules
Polymorphic:
Documents, Images
Now, templates and modules have both documents and images and each Template has many Modules and modules have foreign key that is set to cascade on deletion of templates.
Now, if I delete a Template the associated Modules will be deleted but the associated polymorphic relations of Module will stay in Database. I haven't tried anything because I am completely clueless.
Anything I could do to automatically delete associations of Module when Template is deleted? I think the deletion here in this is being handled by Database itself and Eloquent doesn't have anything to do with it.
Because it is a polymorphic relationship, the cascading delete cannot be handled by a foreign key.
If you still want the deletes to be handled at the database level, you will need to write some type of database trigger functionality.
There are also a couple options if you want to handle this at the application level.
One option is to update your code so that everywhere you delete your Template, you also make sure to delete all of it's polymorphic relations.
Another option would be to create an event handler for the deleting event. The deleting event is fired by Eloquent whenever you delete an Eloquent model. Inside this deleting event, you can access the polymorphic relationship and delete them, as well.
If the deleting event method sounds okay, there is a package that implements all of this for you, and makes it very easy to setup for your models: shiftonelabs/laravel-cascade-deletes. Full disclosure: I wrote the package.
With this package, you just add the CascadesDeletes trait to your Template model, and then add a $cascadeDeletes property that contains an array of all the relationships to delete when a Template instance is deleted.
It's not fully automatic, but I handle it very easy with the destroy() Eloquent method. https://laravel.com/docs/8.x/eloquent#deleting-an-existing-model-by-key In addition, when you will use it with Laravel Queues, it works like a charm...
Example:
$template = Template::find(1);
Module::destroy($template->modules);
$template->delete();
You can actually use delete method on both types of relationship:
$template = Template::find(1);
$template->modules()->delete();
$template->images()->delete();
$template->delete();
Key note here is that $template->modules returns a collection instance while $template->modules() return an eloquent relationship where you can chain delete() method.
I know this is a duplicate question but i think it will help others because there are a lot of similar apps that have these kind of table relationships:
So the question is what would be the optimal solution for all relationships in this schema using the Eloquent?
How many Models and Controllers to make?
First of all, you need to understand that not all tables in a database represent an entity.
For example, tables like users, posts, comments are entities. Whereas posts_users, comments_posts are not: they are here for technical reason, to materialize the relation between 2 entities.
Only entities need a model: it makes no sense to have a model for a relation table.
Even if a table holds information like date_created, it does not make it an entity. This is just a data related to the relation. For example, the table users_roles may have a column named date_assigned, to know when a given user was assigned a given role. It's not entitity for all that.
Second, you need to understand what a controller is for. The role of a controller is to handle a request and provide a result. Result can be a view, an error (HTTP 404), or just the fact that an action has been successfully done.
You must also make the difference between the class called Controller (or any child that extends this base class) and an actual controller. The actual controller is the code that will handle the request. A Controller class can have more than one method to handle requests.
It's all a question of organization: generally, Controller classes are used to group methods within the same scope: user login, logout, subscription, password reminder are all the same scope. All these controllers could be in different classes or functions. It does not matter. Each method is a controller. They are grouped in the same class because they have the same needs (check user is logged in, to know if login is required, if subscription page can be displayed, etc.) and they are in the same scope, which just make sense when you think of it. That's just logical: you know where to search when you need to change something about user identification (even if you are new on the project).
So you need a model for these entities:
User
Offer
Invoice
Category
The controllers you'll need depends on what you want/need to do with this data. There's no ready-to-use answer to this part of your question.
Use a Controller class for:
user authentication (if you need some)
user management (backoffice)
invoice management (edit, mark paid, list of late payments, etc.)
categories management (create, edit, delete)
offers management
But depending on your application, you may need more. Only you can really say. There's no bad answer to this question: if you think some controllers should be separated for better organization, do it. If you think you should group 2 or more, do it. There's no rule. You have to keep your code clear and well organized. It must suit your needs. That's all.
I need some help dealing with a relational table that is an entity due to the existence of an additional property.
Here is a gist of the entities in question: https://gist.github.com/chasepeeler/efd7efd890c58eafb81f
Do I have something configured wrong that is forcing me to do the flush in controller.php line 15?
I've also tried just updating the rank attribute of the queueItem record in the Queue::queueItems collection, but when I do that, it doesn't even save the changes to the database.
$queueItems->clear() does the same thing as clearQueueItems, but one time.
And if you want to override current queue state, you should just implement and call setQueueItems(ArrayCollection $queueItemList) method.
UnitOfWork will compute your changes to insert and remove new/deleted items.
Every OneToMany annotated field should implement setItems, addItem and removeItem methods, where Item is related entity name.
Your sortQueue method shouldn't persist and commit changes into database.
It should only return a sorted Collection.
Maybe I didn't get that, it's hard to say what you want to achieve, controller's code says me nothing.
So I have a lot of controllers that will be created by one user. So on every save/create/update I want the user's ID to be saved the resource's user_id column in the database.
I know that before the actual database update I could go like
$resource->user_id = Auth::user()->id;
but this seems pretty unclean and I don't wanna do this for all the create/update actions I have spread across multiple controllers.
What would be the best and cleanest way to approach this issue?
If you are using Eloquent ORM to define $resource you can define Events for that model, that will be executed (if you wish) after or before every create, update, save, delete or restore action on that model. You can see the documentation here: Laravel 5.1 Model Events Documentation
Create a trait that hooks into the model’s saving event, and set the user ID there.
I currently have a User Doctrine entity and model in my Components. I have a User Bundle that does the basics of working with users, CRUD, etc.
I am developing a resource allocation bundle and I want to extend my User entity to add extra associations without changing the original user. Then the ResourceAllocation Bundle will be completely separate from the User Bundle.
I have setup a mapped superclass of BaseUser, which both User and SkilledUser (the one from the Resource Allocation Bundle). This however, tries to create a table for both User and SkilledUser which is undesired.
The user and skilled user could be the same user, so, Single Table Inheritance is not going to work.
Effectively, the end result should be one table with the users in.
We are working in YAML if answers could keep to this method, that would be great.
"Effectively, the end result should be one table with the users in."
The only way to achieve this is with STI (Single Table Inheritance).
"The user and skilled user could be the same user, so, Single Table Inheritance is not going to work."
I don't see how this matters... you can still create an association between User and SkilledUser if that is what you mean here.
See reference: http://doctrine-orm.readthedocs.org/en/latest/reference/inheritance-mapping.html