Laravel one-to-many relationship with pivot table - php

I have 3 tables in my database. A link table, a question table and an answer table. In link I store evaluationmoments. In question I store the questions that can be asked in the evaluations. In answer I store the answers that a user has given in the evaluation.
What I want to do is get all the answers that were given for a specific evaluation.
Link has the primary key link_ID.
Question has the primary key question_ID.
Answer has the primary key anwer_ID.
Link and Question are connected with a many-to-many relationship. Therefore there is a pivot table called link_question. With the keys link_id and question_id.
In my laravel models I have these functions:
class Link extends Ardent{
public function question(){
return $this->belongsToMany('Question');
}
class Question extends Ardent{
public function link(){
return $this->belongsToMany('Link');
}
This all works fine. However, now I want to give the answer table a many-to-one relation with this pivot table. For every entry in the pivot table there are multiple answers. How would I got about implementing this in laravel? I don't have a model for the pivot table so I can't just add a function there.

Related

Laravel: How to add Relationship in Model when my Foreign keys are in array?

I have a table where I need to save the ids in array, you can see the items in
events_who is a foreign keys. Any solution where I can create a Relationship in my Model to get the data from the foreign keys? I tried belongsToMany and it doesn't work. :(
Any suggestions?
Let's assume we are having 2 models: Event and Person
And a Person can participate to multiple Event
Based on the mentioned relationships, you need to create a pivot table called event_person and define two belongsToMany() relationships in both models:
In the Person model, the relationship will look like:
public function events()
{
return $this->belongsToMany(Event::class, 'event_person');
}
Laravel / MySQL (Relational Database) don't really work this way. You should check out Many to Many Relationships in this case.
Example table schema/layout:
users
|id|name|password|
events
|id|title|body|
event_user (pivot table)
|event_id|user_id|
Usually there won't be an array in a column, you should use tables instead. Besides, normally a foreign key would be a table name(singular) following by _id.

Relationships with same foreign key to same table Laravel 5

I am building a referral system, the table User is referred by another, for example:
User table:
id
name
Referrals table:
id
referred_by (user_id)
refers_to (user_id)
Same foreign key to the same table. Which are the relationships between User table and Referrals?
I am assuming your user model is App\User and your Referral model is App\Referral:
If you want to get, via your user, who they have referred you can do in App\User:
function referredBy() {
return $this->hasMany('App\Referral', 'referred_by');
}
If you want to get, via your user, who they were referred by:
function referredTo() {
return $this->hasMany('App\Referral', 'refers_to');
}
Anywhere you have a $user object, you can get a list of all other referenced users by $user->referredTo() or $user->referredBy()
The Eloquent models allow you to create many different style relations with different key names.
Reference: https://laravel.com/docs/5.5/eloquent-relationships#introduction
The question is bit-ambiguous but if you want relationship in same table it can be done like this -
When building a table 'referrals_table' in the schema -
$table->foreign('refers_to')->references('referred_by')->on('referrals_table')
In the model the relationship will be (assuming name of this model file is ReferralTable) -
public function name_your_function() {
returns $this->belongsTo(ReferralTable::class)
}
You can call this function now to use it.

Multi relations Laravel 5

I have three tables: groups, questions and answers.
groups is connected to questions in a one to many relationship. Similarly, questions has a one to many relationship with answers. Editors provide an answer to a given question after an admin submits the groups and questions.
How do I create this in Laravel 5? I think to creating a pivot table for group_question and question_answer is the right place to start, but I am not sure because I don't know how to later select questions and answers together. Should I instead use json and save all questions and answers to one record?
There are a number of ways to tackle your problem in Laravel, but the easiest way is probably by using the hasManyThrough relationship. Which can be defined in your Group class something like this:
class Group extends Model {
public function answers(){
return $this->hasManyThrough('App\Answer','App\Question');
}
}
just be sure your tables have the following foreign key fields
groups
id - integer
name - string
questions
id - integer
group_id - integer
text - string
answers
id - integer
question_id - integer
text - string
you can read up on more on this in the laravel docs under eloquent relationships.
See more from Laravel 5's docs on the hasManyThrough relationship here.

Laravel, do I need multiple database tables for votes on different models

I have a Question model which has a one to many relationship with an Answer model.
Now I want to add upvote/downvote funcionality to both of these models, do I need to create two tables like VotesQuestions and VotesAnswers or can I somehow manage with one? If so, how?
You can use a polymorphic relationship. This is built into Laravel. Documentation is here. The code shown here is for Laravel 4, but the functionality is the same for Laravel 5.
Create a votes table, and make sure it has at least two specific fields: votable_id and votable_type. In a database migration, you would use the statement $table->morphs('votable');, and it will create the two fields. You can have as many other fields as you like, but to make sure the relationship works, those two fields are required.
Next, setup the Vote model with the votable relationship. The name of this relationship should match the base name of the fields you created:
class Vote extends Eloquent {
public function votable() {
return $this->morphTo();
}
}
With this setup, you can now associate votes to any model you want. Go ahead and add the votes relationship to the Question and Answer models:
class Question extends Eloquent {
public function votes() {
return $this->morphMany('Vote', 'votable');
}
}
class Answer extends Eloquent {
public function votes() {
return $this->morphMany('Vote', 'votable');
}
}
You can now access the votes for any question/answer through the relationship:
$q = Question::first();
$qVotes = $q->votes; // Collection of votes for the question.
$a = Answer::first();
$aVotes = $a->votes; // Collection of votes for the answer.
You can also get the related question/answer model through the vote, if you ever need to:
$v = Vote::first();
$vRelated = $v->votable; // Will automatically be a Question or Answer object, depending on what the vote was for.
I would do an table for the question and when you want to up/downvote the question there should be a count column for both, otherwise you want to log it that an user can only vote for it once, so you need another table for user_id, question_id and type (up/down).
ofc you can handle it with one table, but that is really worth because you save many things that are not necessary.
you can create a table with an internal id, 1,2,3,4 and 1 is always the question or 0 and 2-xx (1-xxx) are always the answers. so you can handle it with one table
You could create a generic Votes model/table which has a field called "model" and "model_id" and then use reflection to get the correct object.

two foreign keys, how to map with laravel eloquent

I have two tables in MySQL, where the first one is called users and the second one is called games. The table structure is as follows.
users
id (primary)
email
password
real_name
games
id (Primary)
user_one_id (foreign)
user_one_score
user_two_id (foreign)
user_two_score
My games table is holding two foreign relations to two users.
My question is how do I make the model relations for this table structure?? - According to the laravel documentation, I should make a function inside the model and bind it with its relations
for instance
public function users()
{
$this->belongsTo('game');
}
however I can't seem to find anything in the documentation telling me how to deal with two foreign keys. like in my table structure above.
I hope you can help me along the way here.
Thank you
A migration:
$table->integer('player1')->unsigned();
$table->foreign('player1')->references('id')->on('users')->onDelete('cascade');
$table->integer('player2')->unsigned();
$table->foreign('player2')->references('id')->on('users')->onDelete('cascade');
And a Model:
public function player1()
{
$this->belongsTo('Game', 'player1');
}
public function player2()
{
$this->belongsTo('Game', 'player2');
}
EDIT
changed 'game' to 'Game' as user deczo suggested.
Unfortunately the way you have this setup is not likely to work in the current context. You may have more luck with the belongsTo method, but again that only supports one relationship.
You could implement a user1() belongsTo, a user2() belongsTo and finally just declare a non eloquent function to return both (something like $users = array($this->user1(), $this->user2())

Categories