I followed Jeffrey Way's ManyToMany tutorial https://laracasts.com/series/laravel-5-fundamentals/episodes/21 and I got everything and everything is working great. However I would like to add another feature to my many to many relation and that is a 'comment' that gives some more info to the object relation.
I have two models:
Article [id, title, text]
Category [id, title]
And this is a many to many relation so I create a pivot table as article_category. This table has two columns article_id and category_id and they are connected via functions in model as:
Article.php:
public function categories()
{
return $this->belongsTo('App\Category');
}
& Category.php
public function articles()
{
return $this->belongsTo('App\Article');
}
However I would like to add another field called comment to the pivot table where I could describe why this Article was added to this specific Category. Adding a column is not a problem but I don't know how to retrieve this comment from, lets say, Article instance:
$articleCategoryComment = Article::find(1)->commentFromPivotTable;
I could always define another oneToMany relation, and create another table to save the comment with fields [artice_id,category_id,comment] but I am wondering is there a better/simpler way.
Also, any good resource on database structuring will be greatly appreciated. I would prefere bunch of examples on how to do stuff right way in MySQL but a book that explains things from scratch is also good recommendation. However, at the moment I won't have time to go too deep but it will be bookmarked for future reading.
Thanks!
You should be using belongsToMany on a Many to Many relationship. If you want additional columns on your pivot table, using the withPivot() method. From the docs:
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
You'll find more info here: http://laravel.com/docs/master/eloquent-relationships#many-to-many
Related
I am currently working on a symfony 6 project with a mysql database and have the following issue:
My situation:
I have two tables/entities:
Orders
Article
This two entities are related in a many to many relationship. So one order can have many articles and one article can belong to many orders.
This relationship leads to the creation of a third table that links the other two tables in terms of the many to many relationship.
The Problem:
I am now wondering where to store the information about which Article gets ordered how often.
My Idea:
I thought about storing this information in the linking table. However normally Symfony does not create an Entity for this. Therefore I think that there might be a better solution.
Does anybody have Idea where to store this information? :)
Thanks to #Cerad I found out, that when there is the need for storing such extra information, a Many To Many Relationship is not the right answer.
In a case like this, it makes sense to create a further Entity like OrderArticle. This Entity is in a many to one relation with both Orders and Articles.
As also stated in the Symfonycasts Tutorial here: https://symfonycasts.com/screencast/symfony4-doctrine-relations/many-to-many-joins
Maybe this helps someone in the future as well. :)
I am using Laravel to build a small customer list system.
I need to link COMPANY with CONTACT_PERSON. In a normal situation, I can use many to many pivot tables to link and update them.
However, I need to keep historical records. That means the same person can act as a contact in the period earlier, resigned, and reappointed later with another period.
I try to duplicate the pivot table entries with phpMyAdmin, makes the same COMPANY linked the same CONTACT_PERSON twice, and two entries were found when retrieving the COMPANY records.
However, how can use Laravel duplicate the entries? How to use Laravel to CURD those. Or I just do it in the wrong way?
Thank you very much!
EDIT :
Example :
Company A employed Mr. A between 01-01-2001 till 02-02-2001,
Compnay A employed Mr. A again on 03-03-2001 till 04-04-2001.
There are company B,C,D ... in company table,
There are Mr. B, C , D in the employee table too.
Use Laravel relationship pivot table to link company A to Mr. A will have two records in the above case (I need to have a historical record).
Is it the right way to handle such cases with Laravel many to many relationships? Or I should consider other ways ?
A pivot table can contain additional columns. You could consider adding migrations that add a started_at and resigned_at datetime field to your pivot table.
Your data structure would look something like this:
Company
id
...
Contact_person_company
contact_person_id
company_id
started_at
resigned_at
Contact person
id
...
After that, you could create functions in your model to work with the pivot columns and check for their status. A null value for the resigned_at column indicates that the ContactPerson is still active.
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Company extends Model
{
// ... other functions
public function contactPersons(): BelongsToMany
{
$this->belongsToMany(Company::class)
->withPivot('started_at', 'resigned_at')
->wherePivotNull('resigned_at');
}
public function resignedContactPersons()
{
$this->belongsToMany(Company::class)
->withPivot('started_at', 'resigned_at')
->wherePivotNotNull('resigned_at');
}
}
You should define these functions as well on the ContactPerson model.
If the logic gets very complicated, consider creating a Pivot model (CompanyContactPerson).
Please note that the combination of contact_person_id, company_id started_at should be unique. Otherwise, considering adding a primary key like ID the company_contact_person table to identify these records.
I have a table for publications, which has a relationship of one-to-many with the table reviews, each publication has many reviews.
I'm using AngularJS for the frontend and Laravel for the backend and MySQL for the database.
Let's say I would softDeletes() one of the publication, should I also need to use softDeletes() to all of its reviews? When softDeletes() is used with the parent, what is the best way to handle all of its child
Currently this is the solutions that I can think of base on my research but I still have doubts to what is the best way regarding of performance :
1. Only update the deleted_at column in publications table and leave
the reviews table as it is.
2. Create a MySQL trigger to update the deleted_at column in reviews
table when user softDeletes() the publication.
3. Update deleted_at column in table reviews inside laravel controller,
which will use foreach. But I think this has a performance issue assuming
that the publication have hundreds or thousands of reviews.
4. Create a different table for reviews which parent is temporarily inactive.
Separating reviews that are active and inactive, I think this will help in
query performance. I'm not sure.
Sorry if some of my grammar is wrong but if you understand my question I would be happy to hear your thoughts. Thank you.
Do you need to do anything at all?
If you can't access single reviews without going through the parent->child relationship, there's no real reason to do anything with the reviews.
If you can access single reviews, just add a constraint to not fetch reviews where the parent is softdeleted()
But if you don't like that approach, just enable softdeletes on your reviews and when you destroy() a publication:
foreach($publication->reviews as $review) {
$review->delete();
}
Laravel's Eloquent model events are likely the best bet here.
Model::deleted(function ($model) {
$model->children()->update(['deleted_at', $model->deleted_at]);
});
Model::restored(function ($model) {
$model->children()->update(['deleted_at', null]);
});
I can't find a way to define relationships. Here is my previous question, you can review it to find what I'm looking for: PHP/Laravel/Bootsrap fetch data
I've defined the relationship for skills like this:
public function skills()
{
return $this->hasMany('Skill', 'player_skills', 'skillid', 'player_id');
}
Still getting the Undefined property: Illuminate\Database\Eloquent\Collection::$players error pointing at $skills->players as $player.
First of all, with the hasMany function, you are setting up a one-to-many relationship, but it looks like you are sending it the name of a pivot table as a parameter, which would only be required for a many-to-many.
I'm going to assume you actually want a many to many relationship and your keys are correct (they are in the question you linked, but skillid is different here, so let's go with skill_id)
Also, the way you are looping through the data is wrong. $players->skills doesn't make any sense because $players doesn't have skills, but $player does.
Here is what I have so far... http://paste.laravel.com/Jp8
With the newest information you have given, I think there might be some confusion about how a many-to-many relationship works in Laravel. Please check this out when you get a chance, it should be pretty close to what you are looking for... http://paste.laravel.com/JqV
So... I have 2 tables:
banner_channel
banners
I need to create a table to relate the banners (table banners) with the channels of the banners (table banner_channel).
Obs.: I cant rename table banner_channel to channel only because I already have this table in database.
Maybe, the new table is:
banners_banner_channel
or
banners_channel
? I dont know.
Anyway, thanks.
Sorry for my english... I'm brazilian 8D
First of all according to the cakePHP naming conventions the table you named banner_channel should be in plurals: banner_channels
As for the naming, it should be:
banners_banner_channels
CakePHP cheat sheat
banners_banner_channel is the correct table name according to what you have already.
just have a look at all the options in the habtm relations as you will have to set them all manually. instead of just doing 'hasAndBelongsToMany' => array('BannerChannels') you will need to set everything according to this
first example: you will need atleast the following, className, joinTable, foreignKey, associationForeignKey and with
the rest you can tweak to your needs