laravel models fill additional field inside many-to-many table - php

I am a newbie at Laravel framework and trying to work me in.
I already understand how to generate N:M relationships and handle them inside the models. Now I am asking you how to fill an additional field inside the many to many tables?
For example:
Table Foo
Table User_Foo
user_id
foo_id
is_owner (bool)
Table User
Now I want to declare which of the foo users is the real owner.
In my opinion, the N:M Table has stored this information an not the Foo itself.
So how is it possible to declare those additional fields inside of my Foo and User model?

Retrieve additional fields you can with withPivot() method
return $this->belongsToMany('App\User')->withPivot('is_owner');
Fill you can with sync() or attach() methods.
Laravel relations doc

Laravel provides us with concept of pivotwhen defining N-M relationships. By default the table will have the both connected keys. But if you want to add extra fields in that bridge table.
$model->belongsToMany('Model')->withPivot('column1', 'column2');
In above case, your pivot table will have two additional columns and you can access these columns as:
$model->pivot->column1
$model->pivot->column2

Related

Laravel many to many with a pivot relationship.

User
uid
Provider
pid
Resolution
rid
ProviderResolution
prid
pid
rid
active
ProviderResolutionUser
prid
uid
class Provider extends Model {
public function resolutions()
{
return $this->belongsToMany('App\Models\Resolution')->withPivot('active')->withTimestamps();
}
}
class Resolution extends Model {
public function providers()
{
return $this->belongsToMany('App\Models\Provider')->withPivot('active')->withTimestamps();
}
}
class User extends Model
{
}
Trying to create a Eloquent relationship with this.
I'm trying to figure out how to fit user into this model. It seems like it's suppose to belongsToMany. Do I need to create a class that represents the pivot?
Then from the case of the User how would I query a list resolutions?
You didn't ask but I personally think it's a lot easier to let the primary key of each table be 'id.' Also, in the case of ProviderResolution, unless you have a specific case for it, you don't need (and shouldn't use) 'prid' at all. Just 'pid', 'rid' and 'active' should be sufficient. The 'pid' and 'rid' make the composite primary key on their own. If you add yet another key ('prid'), then there will be a three-key composite which will technically enable you to have duplicates with your other two primary keys. Yuck. Example: PRID:1, PID:1, RID:1, then PRID:2, PID:1, RID:1. Now you have duplicates but your record is technically still unique because of the PRID key. But, maybe you want it this way for some reason?
For the answer I'm going to assume you are using Laravel 5.4+.
So first off, you don't need a class for the pivot. And secondly, you are currently trying to create a relationship between the user and the existing pivot table between Provider and Resolution by creating a table called 'provider_resolution_user'. If you want to query resolutions for a user, just use the relationship methods which gives you access to the attributes on the pivot table and the related models/tables.
First, setup the 'hasMany' relationships in both classes: Users and Resolutions (Providers already has a relationship to Resolutions, so you can use that relationship if you want to see the related Provider.) Then you'll need a pivot table called 'resolution_user'. Put the 'uid' and the 'rid' in the table. Make the relationships to the corresponding foreign key fields to their parent tables.
Now you can access the relationship directly like:
$user->resolutions->rid (or whatever the attribute is you want)
The previous example assumes you have already created a way to insert records into the pivot table (resolution_user) that relate the user and the resolution together.
If you want to access one of the attributes on the pivot table, 'pivot' creates an object instance with it's own attributes (from the table). You can access it like this:
$user->resolutions->pivot->active;
Of course, these methods are chainable so if you just wanted to see the active resolutions, you could also add a ->where statement.
Hope that helps and wasn't too muddy. I'm happy to clarify any points if need be.
EDITED ANSWER:
Because what you want to do is to disable a row in the provider_resolution table and have that reflect on the correct user, then just create a relationship in both the User model and the Resolution model. So when you disable a row in provider_resolution (pid, rid, active), you can lookup the appropriate user to update by using the inverse relationship between resolution and user. This should give you the user that is assigned to that particular resolution/provider combination. If for some reason you do need to find the user based on a unique combination of the TWO: resolution AND provider, then we might need to talk about polymorphic relationships. Let me know.

How to get value from column that is in a N-N relationship table in Laravel

Im having a problem. I have two tables, places and cuisines, and cuisine_place and in that table I have a column called default (that shows if that cuisine is the default cuisine for that place). But Im having the problem that Im not able to access to that column.
How can I do?
What I want to do is have them in this answer:
$places = Place::all()->with('cuisines')->withPivot('default');
Something like that.
Thanks
You have a many to many relationship between places and cuisines. That relationship would be defined in the following fashion in your models:
public function cuisines(){
return $this->belongsToMany('Cuisine', 'cuisine_place');
}
The above would be a function in your Place class that references its relationship to the cuisines table. By default, Eloquent will pick up the foreign keys in the cuisine_place table (in your case they would probably be called cuisine_id and place_id). If you want to pick up additional columns from that table on calls to the above relationship function, you can use the withPivot function:
public function cuisines(){
return $this->belongsToMany('Cuisine', 'cuisine_place')->withPivot('default');
}
Now, on calls to the cuisines() method in your Place class, you'll receive the default column in the object associated with that table.
Open documentation for Laravel Eloquent Relationships
And read about Retrieving Intermediate Table Columns
You didn't provide your models code so it's difficult to help you with the exact solution

Dynamic tables and models in Laravel 5

I have the next tables:
pages
id
title
...
dynamic_table_1_infos
id
page_id
image_id
dynamic_field_1
dynamic_field_2
...
dynamic_table_2_infos
...
So there are "one to many" relationships.
Is there any way to use a general approach without creating a DynamicTable[No]Info model "on the fly" for each table?
And what if I will need some extra methods in these models?
The "Page" model will have many relationships with "dynamic_table_[no]_infos" tables. So I will probably need a general method for doing this.
(Has many dynamic_table_1_infos / has many dynamic_table_2_infos ...)
What I am trying to do is somehow inspired by Dupal`s content types.
If you want to save a single model data to multiple tables depending on the value of some model attribute, you'll need to override model's getTable() method to return the name of the table it should write to.
I'm not sure how you want to decide to which table Eloquent should save to - for example, if you had an attribute called segment in your mode, you could just do:
public function getTable() {
return 'dynamic_table_' . $this->segment . '_infos';
}

Fetching all pivot table columns via custom pivot type

I have a many-to-many relationship where the pivot table has about 20 additional columns. I am using a custom pivot class, and I have successfully set up the code to return an instance of that class when the ->pivot property is accessed on the relation, e.g.
$supplier->products->pivot returns the custom pivot class.
However, when wanting to access the data, I can manually define all the individual attributes of the pivot class (which extends Pivot by the way) in the belongsToMany relationship like this:
return $this->belongsToMany(Product::class, ['prop1', 'prop2', 'prop3'])
...But, how can I retrieve all the pivot data of the class without manually defining them as it ties the relationship declaration very close to the class? Is this possible. If not, it's going to make maintainability a PITA! Ideally, it'd be really nice if withPivot just had a flag to get it all!
In my circumstances, I found it easier to separate all the data into a separate table and model, and add a foreign key in the pivot table to the additional table record. This allows me to use the 'normal' model handling in Laravel and means I don't have to mess around with problems like this!
My use case was a schema of product and supplier with a many-to-many, and each supplier having their own data for the product, namely price, stock, shipping cost / times etc, so I moved all this from the pivot to a SupplierProduct model.
I'll leave this question here, as although this isn't the direct answer to the question (which I fear the answer is 'no'), this is a solution which is viable and can save quite a bit of coding frustration!

Difference between HABTM relationship and 2 $belongsTo relationship with a third model

I'm creating a project management system which projects are assigned to users
What's the difference between creating a Model ProjectsUser and defining 2 $belongsTo relationship and defining HABTM relationships in both Project and User models? What would be the most correct way, though? And how do I save the data in the projects_users table?
From my experience, if you want to be able to save or delete rows only from the join table (the one with 2 IDs), then it is much more simple using three models associated through both a hasMany and a belongsTo association.
You can also retrieve data from the join table directly and do the queries you want much more easily
This is what CakePHP documentation says refering to HABTM and saving data:
However, in most cases it’s easier to make a model for the join table and setup hasMany, belongsTo associations as shown in example above instead of using HABTM association.
Here you can find more the full text:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated
I have used this method for a "reads" table (with post_id and user_id) as well as for subscriptions and similar kind of relationships.
The first way is called "hasAndBelongsToMany" [details here].
The second is called "hasMany through" [details here].
The second link relating to "hasMany through" has details and a lengthy explanation about when and why you would want to use it.
Not sure about the specifics of cakephp, but in general defining the relation model explicitly gives you more control over it, for instance if you wanted to do some validation or add callbacks on creation of this relationship.

Categories