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';
}
Related
In this figure, the remaining tables are linked to the datainfo table. I need to retrieve the entire table data from the datainfo table.
In this picture I have shown the tables themselves
You can create Eloquent Models for each table and define Relationships among them. This is the Correct Laravel Way.
Let's assume Your datainfo table represents your Datainfo model,
Your cars table represents Car model. Same as washtypes and boxes.
then depending on your relation type defined the relation in Datainfo model.
class Datainfo extends Model
{
public function cars()
{
return $this->hasMany(Car::class);
}
}
You also can use hasOne instead of hasMany for one - to one relation
Similarly, create relation defining functions as washtypes() and boxes().
Then To get Datainfo with all related data using something like think in your controller
return Datainfo::with('cars','washtypes','boxes')->get();
Alternatively, you can get the count
return Datainfo::with('cars','washtypes','boxes')->count();
To get a count on a date
return Datainfo::with('cars','washtypes','boxes')->where('created_at',$date_var)->count();
If you only want Datainfo that has relation with cars, washtypes or boxes:
return Datainfo::has('cars','washtypes','boxes')->where('created_at',$date_var)->count();
Use laravel eloquent join clauses, https://laravel.com/docs/8.x/queries#joins
For total amount in same day
You can use eloquent sum and group by methods based on the date
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
I have 3 tables namely A, B and C.
All 3 of them need to make use of a notes table(i.e. A has many notes and a note belongs to A. The same follows for remaining 2 tables).
So I created 3 more tables: A_note, B_note and C_note(as mentioned here: multiple tables need one to many relationship).
Is there a way to do CRUD operations on these tables(A_note, B_note and C_note) similar to the way we handle pivot table in many-to-many relationship?
Please suggest a way forward.
You should be using polymorphic relationships for this. It allows multiple models to make use of a single table.
Have a look at the documentation here
In your particular case, each of your tables would reference a noteable_id column and a noteable_type.
The noteable_id will contain the id of the (A/B/C) model.
The noteable_type will contain the string name of the model (A/B/C).
The (A/B/C) models will now get a new attribute:
/**
* (A/B/C) Model(s)
*/
public function notes()
{
return $this->morphMany('App\Notes', 'noteable');
}
And the note model will initiate it's polymorphic properties against the attribute name used to identify your polymorphic ids and types:
/**
* Note Model
*/
public function noteable()
{
return $this->morphTo();
}
Now you can simply call ->noteable on the (A/B/C) models, and they all share 1 table without the need of another pivot table for each table.
I'm trying to get my head around using polymorphic relationships for a many-to-many relationship between suppliers and products:
products
id
name
suppliers
id
name
product_supplier
id
product_id // belongsToMany easily takes care of this id
supplier_id // and this id
price // this can be fetched using withPivot('price')
deliverymethod_id // I'm having difficulties "joining" this one.
I'm confident in using belongsToMany(), I can easily do something like this:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price');
}
But the catch here is joining to that third column in the relationship table:
deliverymethods
id
name
I am unsure how to do this. I've been told that Polymorphic Relationships are what I'm after however I'm unsure how to implement them for my situation.
http://laravel.com/docs/4.2/eloquent#many-to-many-polymorphic-relations
According to the documentation, I would have to rename my table columns to include *able_id and *able_type. This is really confusing.
I was expecting laravel to having something like belongsToMany('Supplier')->withAlso('Deliverymethod')
I'm afraid that method does not exist (yet?).
What I fall back to is manually filling in the 3rd relation:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price', 'delivermethod_id');
}
Now I can access ->pivot->deliverymethod_id on every Product that I get via Supplier.
You could even add a function in your Product model that fills this in automatically:
Class Product ... {
protected $appends = array('deliverymethod');
public function getDeliverymethodAttribute()
{
return Deliverymethod::find($this->pivot->delivermethod_id);
}
Now every time you request a product via it's relation to the supplier, it automatically includes a deliverymethod attribute with the object in it.
(To have it not throw an error when you get a Product directly, just remove the $appends variable from the Product model and call the getDeliverymethodAttribute() method manually whenever you need it.)
Short explanation about polymorphic relations:
Polymorphic relations are for relations, where two models are related to a third model at the same time. So for example both a User and a Product can have a Picture of them. Now, it doesn't make sense to have two models for the pictures (UserPicture and ProductPicture), since they both have the same characteristics. This would be a perfect reason to use a polymorphic relation, where the Picture can both belong to a User or a Product.
However, in your case the Deliverymethod applies directly to the relation between Supplier and Product. So this is not where polymorphic relations would work, but it has instead to be done the way you did it.
I would like to have a one to one relationship with a pivot table or by referencing an ID in a table.
I currently have a Films table that has a one to many relationship with a Stock table, each stock item needs a format, however I would like the formats to be a set list of formats so I created a Formats table that only has 2 columns ID and Name
Normally I would just add a Format_ID column to the Stock table however I'm unsure how this would work with the Eloquent ORM or if it's even possible / best practice
Sorry if this is hard to understand, cant quite figure out the best way of explaining it
The structure you desire is pretty standard practice. It's quite possible!
Which Eloquent relationship you'd use depends on the direction of the relationship. Each Stock has one Format (one-to-one). But each Format can be assigned to multiple Stock (one-to-many).
For the former, your Stock Eloquent model would have a hasOne() one-to-one relationship.
class Stock extends Eloquent {
public function format()
{
return $this->hasOne('Format');
}
}
For the latter, your Format eloquent model would have a hasMany() one-to-many relationship.
class Format extends Eloquent {
public function stock()
{
return $this->hasMany('Stock');
}
}
Note that having both of these defined is totally acceptable and normal. It really just depends on which direction you need your relationship to go. If you never need to look up what Stock belongs to a specific Format, you don't need the one-to-many relationship.
Also note that you may need to add a column key parameter if your column names are not easily guessable by Eloquent. E.g.:
return $this->hasOne('Format', 'my_format_id');