Laravel Many-to-many relationship three way - laravel

I'm relatively new to Laravel and currently I am facing this problem:
Let's say I have 3 tables:
Questionnaires
Questions
Answers
The relationships for all of them should be many-to-many. So, I have created two pivot tables:
questionnaire_question
answer_question
However, I have to specify one or more correct answers for each question.
Currently, I have set a 'correct' column in the answer_question pivot table to specify if an answer is correct but this approach does not work for my case...
A specific set of answers could be used to more than one questionnaires and questions that could possibly have different 'correct answers' in each case.
Thus, I was thinking of having a representation of the correct answers to a table where the questionnaire_question id, is associated with many answers.
Is this a concept on the correct path and if so, how could this be accomplished?
I have also considered of Defining Custom Intermediate Table Models as described on the docs, however I am not sure about how this could be implemented in this case where all relations should be many-to-many.
Any help is appreciated!

Related

Laravel Varbox 2.x - duplicate model with relationships included

I’m using the HasDuplicates trait on my Post custom entity.
The Post has 2 relations:
has many comments
has one author
How can I configure the duplicate functionality in order to duplicate a post record along with its relationships: comments and author?
I see in your documentation that I have the option of excluding relations, but not to include them.
The Varbox\Traits\HasDuplicates automatically duplicates all your eloquent model relationships by default, so that's why there's no option to include any relationships to be duplicated, because they all are duplicated by default.
Also, in the event where you don't want certain relations duplicated (such as belongs to relations), you have the option to exclude them (as you already stated): https://varbox.io/docs/2.x/duplicate-records#exclude-relations
So to answer your questions, you don't need to do anything to include your comments and author relations into the duplication functionality, as they will be included by default.
Suggestion: Depending on your database structure and logic architecture, I think you should consider converting the author relation into a belongs to, instead of has one, but that's up to you.

Achieve one to many relationship Spring MVC

I am trying to achieve one to many relationship. I know how to do basic one to many relationship between requestor id and userid.
My question is How to refer gtlUserId(resourceRequestTable) to gtlUserId (User table) as by default spring is mapping gtlUserId (resourceRequestTable) to userId in user table
It has some Ways.
I think you should give a specific way during all project !
As My experience each many to one must be a Drop Down in Client side .
However in your Table ResourceTypeEntity should be drop down inside ResourceRequesTable when value of option is Id[primary Key].
Also Your table not seems good design why two many to one map to same table? it may cause 3NF problem in DB also pay attention Cascade it when Parent Table related to other Parent is not good Design ,Keep it simple with uni Direction Many to One And force user to delete manually parent is better ,CaseCade Delete when Parent has related to other table will make exception handling and testing too hard.
please take a look https://examples.javacodegeeks.com/enterprise-java/spring/mvc/spring-mvc-dropdown-box-example/

how to use where clause on laravel eloquents that depend on relation table?

i have two tables,
one is - question table - and other is - answers table - , answer will have question_id.
I'd like to know how can i filter all questions where not has an answer yet in laravel
so i'm assuming something like
Forum::where(forum->comments->count(), 0)
i already set the relation, of course the code didn't work, just for an example
thanks!
Try this
Question::doesntHave('answers')->get();
if you want the count
Question::doesntHave('answers')->count();

Loading validations from a table

I need to load model validations from a table and validate my model. e.g. I have a database table called validations, which has rows like :
validation_action validation_condition
---------------- --------------------
validates_presence_of if answer_name is name
validates_format_of if answer_type is date
In my model I want:
class Model < ActiveRecord::Base
load validation_actions , lambda {if validation_condition is true}
Ok more detail:
I am creating an app for taking surveys. I am storing questions in a table and answers in another table. I need to store the validation for each answer in the question table and validate each answer before I accept it. I can query validation for each question and run it in controller but I want to do it in model instead as it is much cleaner.
so two models :
Questions -> table questions sas code and details about questions
Answers -> table answers stores answers with a foreign key to Questions.
I want to validate the input in Answers model depending upon conditions defined in questions database table.
Please let me know if more detail is needed?
If I understand correctly, you have Questions which have many associated Answers, and also have associated ValidationActions. When an Answer is being saved, you want to run validations against it based on evaluating code stored in the ValidationActions belonging to it's associated Question object.
This seems like a bad idea. Not so much that validations are conditional on the state of an associated object (the Question), which is the sort of thing that does happen, but that you're doing what amounts to executing code from the contents of the database. This is one of those things that makes web developers twitchy - the security issue is the most obvious reason (that if someone can edit your database's fields, they can cause arbitrary code to run on your system), but it's definitely a questionable practice even outside that (I'm having trouble articulating the reason more convincingly than 'code is code and data is data and never the twain shall meet', but there it is).
All that said, it should be possible to write a custom validator as explained here to handle this. It will doubtless be inefficient, might well be prone to breakage, and is probably a security hole unless it's written very carefully. But it's possible.

When would it be worth it to maintain an inverse relationship in Doctrine2?

In the Doctrine manual, under Constrain relationships as much as possible, it gives the advice "Eliminate nonessential associations" and "avoid bidirectional associations if possible". I don't understand what criteria would make an association "essential".
I say this because it seems that you would often want to go from the One side of a One-to-Many association rather than from the Many side. For example, I would want to get all of a User's active PhoneNumbers, rather than get all active PhoneNumbers and their associated User. This becomes more important when you have to traverse multiple One-to-Many relations, e.g. if you wanted to see all Users with a MissedCall from the last two days (MissedCall->PhoneNumber->User).
This is how the simple case would look with an inverse association:
SELECT * FROM User u
LEFT JOIN u.PhoneNumbers p WITH p.active
It would make it more sensible if there were a way to go across a given relation in the opposite direction in DQL, like the following raw SQL:
SELECT * FROM User u
LEFT JOIN PhoneNumber p ON p.User_id = u.id AND p.active
Can someone explain why they give this advice, and in what cases it would be worth ignoring?
-- Edit --
If there are mitigating factors or other workarounds, please give me simple example code or a link.
I do not see any way to traverse a relation's inverse when that inverse is not defined, so I'm going to assume that building custom DQL is not in fact a solution -- there are some joins that are trivial with SQL that are impossible with DQL, and hydration probably wouldn't work anyway. This is why I don't understand why adding inverse relations is a bad idea.
Using Doctrine, I only define relationships when they're needed. This means that all of the relationships defined are actually used in the codebase.
For projects with a large team working on different areas of the project, not everyone will be accustomed to Doctrine, it's current configuration, and eager/lazy loading relationships. If you define bi-directional relationships where they aren't essential and possibly don't make sense, it could potentially lead to extra queries for data that:
may not be used
may have been selected previously
Defining only essential relationships will allow you greater control over how you and your team traverse through your data and reduce extra or overly large queries
Updated 22/08/2011
By essential relationships, I mean the ones you use. It doesn't make sense to define a relationship you wouldn't use. For example:
\Entity\Post has a defined relationship to both \Entity\User and \Entity\Comment
Use $post->user to get author
Use $post->comments to get all comments
\Entity\User has a defined relationship to both \Entity\Post and \Entity\Comment
Use $user->posts to get all user posts
Use $user->comments to get all user comments
\Entity\Comment only has a relationship to \Entity\User
Use $comment->user to get author
Cannot use $comment->post as I don't retrieve the post it belongs to in my application
I wouldn't think of them as "Inverse" relationships. Think of them as "Bi-directional", if using the data in both directions makes sense. If it doesn't make sense, or you wouldn't use the data that way around, don't define it.
I hope this makes sense
I think this is a great question, and am looking forward to others' answers.
Generally, I've interpreted the advice you cited in the down to the following rule of thumb:
If I don't need to access the (inverse) association inside my entity, then I typically make it unidirectional. In your example of users and (missed) calls, I'd probably keep it unidirectional, and let some service class or repository handle putting together custom DQL for the odd occurrence when I needed to get a list of all users with recent missed calls. That's a case I'd consider exceptional -- most of the time, I'm just interested in a particular user's calls, so the unidirectional relationship works (at least until I've got so many records that I feel the need to optimize).

Resources