laravel polymorphic relation custom type - laravel

I have an Image table as follow:
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('path');
$table->unsignedBigInteger('imageable_id')->nullable();
$table->string('imageable_type')->nullable();
$table->unsignedBigInteger('image_properties_id')->nullable();
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
I want to have polymorphic relation with images table and it works fine for most parts however the problem here is that some Models such as Post can have images for different purpose, for instance a post can have a image for post's cover and also images used in the post content.
Is it possible to access only images belonging to post's cover and not content?
I know that I can define custom type using morphmap, but is it possible to define two different types that points to the same Model and use these type to filter the results?

You can use the extended relationship to filter out as required.
Assuming you have images relationship on Post model, you can create two more as follows (one each for content and cover)
public function coverImages() {
return $this->images()->where('imageable_type', 'post/cover');
}
public function contentImages() {
return $this->images()->where('imageable_type', 'post/content');
}
With those relationships definition, now you can use each of them as an independent eloquent relationship.

Related

Can I create a double-morphed many-to-many relationship in Laravel?

I have two models: Product and Group, which I want to both give a many-to-many 'shown' and a 'recommended' relation with itself and the other (so both have has to be morphed in both ways).
So a 'shown' resource of either type has a set of 'recommended' resources of either type (the Groups are actually acting as a container for grouped Products).
The table should be pretty straightforward:
Schema::create('recommendables', function (Blueprint $table) {
$table->id();
$table->morphs('shown');
$table->morphs('recommendable');
$table->timestamps();
});
Then relations are defined in the trait 'RecommendableTrait' which is then given to both classes. As far as these relationships are concerned both classes are then handled pretty much the same later on (even to be merged into a single collection), so there is merit in trying to do it this way.
The problem is that the following relation definitions won't work, because it will look for group_id if I call the morphed relations on Group, similarly with `morphedByMany'.
trait RecommendableTrait {
// RECOMMENDED GROUPS
public function recommendedGroups()
{
return $this->morphToMany(Group::class, 'recommendable', 'recommendables')
->withTimestamps();
}
// RECOMMENDED PRODUCTS
public function recommendedProducts()
{
return $this->morphToMany(Product::class, 'recommendable', 'recommendables')
->withTimestamps();
}
// SHOWN GROUPS
public function shownGroups()
{
return $this->morphToMany(Group::class, 'shown', 'recommendables')
->withTimestamps();
}
// SHOWN PRODUCTS
public function shownProducts()
{
return $this->morphToMany(Product::class, 'shown', 'recommendables')
->withTimestamps();
}
}
Now I know, I'm looking to create a bit of a weird relation tangle here. But I'm hoping defining a double-morphed many-to-many is possible in Laravel?
If not, I guess I'll have to either split it up in two single-morphed many-to-Many relationship sets for both classes. Which would be annoying because of the code that goes on top of these relations would have to be needlessly duplicated. Or I'll have to forego relations and just DB query the results directly. Thus giving up some of Eloquence's convenience, but at least allowing me to keep the code confined to a single shared trait.

Struggling to define a polymorphic relationship which includes a BelongsTo

I'm working on a text-based, rng-based motorsport "simulator" and I'm now at the point where I want to add qualifying. Since there's many different types of qualifying sessions across real life motorsport, I want to give the user the ability to use whatever format they like.
I have a Season model, to which the a qualifying format will belong. The different formats are defined as separate models themselves, for example ThreeSessionElimination and SingleSession. The migrations for these would look something like this;
Schema::create('three_session_eliminations', function (Blueprint $table) {
$table->unsignedBigInteger('id')->primary();
$table->foreignId('season_id')->constrained();
$table->unsignedInteger('q2_driver_count');
$table->unsignedInteger('q3_driver_count');
$table->unsignedInteger('runs_per_session');
$table->unsignedInteger('min_rng');
$table->unsignedInteger('max_rng');
$table->timestamps();
});
and
Schema::create('single_sessions', function (Blueprint $table) {
$table->unsignedBigInteger('id')->primary();
$table->foreignId('season_id')->constrained();
$table->unsignedInteger('runs_per_session');
$table->unsignedInteger('min_rng');
$table->unsignedInteger('max_rng');
$table->timestamps();
});
My initial thought was to add
public function season(): BelongsTo
{
return $this->belongsTo(Season::class);
}
to each qualifying format model, but obviously the inverse can't be a HasOne since there's different tables for each different format.
I've had a look at the "One To Many (Polymorphic)" relation documentation, but I can't quite wrap my head around how I should apply that in my case. Would I have to add a qualifying_format_id and qualifying_format_type to my Season model and remove the season_id column from each format migration to make this work?

How to model a dependency graph in Laravel

I am stuck modelling the following relationship in a new application:
A Module can require (many) other Modules.
In Laravel I added the Module model and a ModuleRequirement model with its migrations. The second one has a foreign id field for the module it belongs to:
Schema::create('module_requirements', function (Blueprint $table) {
$table->id();
$table->foreignId('module_id')->constrained();
// How to reference other modules?
$table->integer('requires');
});
The relationship itself is defined by:
// Module.php
public function moduleRequirements()
{
return $this->hasMany(ModuleRequirement::class);
}
This method returns a collection of ModuleRequirements as expected. Unfortunately in order to get the real Module objects I need a foreach loop and build my own collection. I wonder if there is a simpler and faster solution. The perfect way I could imagine is sth. like $module->moduleRequirements returning a collection of the actual models instead of its ids.
My understanding that a module has relation with other modules in the same table.
you should use many to many relationship ,in that case you will not need a model for ModuleRequirement just a pivot table would be sufficient.
In your case module_requirements would act as the pivot table and you just need to change the relation in Module.php to :-
public function moduleRequirements(){
return $this->belongsTomany(Module::class,"module_requirements", 'module_id', 'requires');
}
the migration should be something like :-
Schema::create('module_requirements', function (Blueprint $table) {
$table->foreignId('module_id');
$table->foreignId('requires');
$table->foreign('module_id')->references('id')->on('models')->onDelete('cascade');
$table->foreign('requires')->references('id')->on('models')->onDelete('cascade');
});

Best practice for storing a polymorphic belongsTo relation

We have a need for multiple models to share a documents relation. Due to that, I've used a polymorphic one to many as per the below schema.
Schema::create('client', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('documents', function (Blueprint $table) {
$table->id();
$table->foreignId('type_id')->constrained('document_types');
$table->string('path'),
$table->morphTo('documentable');
});
Documents Model
public function documentable()
{
return $this->morphTo();
}
Client Model
public function documents()
{
return $this->morphMany(Document::class, 'documentable');
}
Each document will need to relate to a specific type. For example, one document might relate to the customers signed agreement and another may relate to a completely different document - These types will need to be 'query-able'.
What's the best way to proceed with this? As far as I'm aware, my options are;
Create a document_types table and set a belongsTo relation on the documents table.
Create an enum column on the documents table.
A side note on this. This will be consumed via an API. There will be the following resources:
Route::apiResource('client', 'ClientController');
Route::apiResource('client.documents', 'ClientDocumentController');
With whichever solution is proposed above, how would you propose the API handles the document type when creating/updating a document?
If the use of a documents_type table, would the end-user have to hit a resource for the document type, to obtain the document type ID prior to creating/updating a document?
If the use of enums, would the API just expect a string for the given document type?
Many thanks in advance.

Laravel 5 - defining relationships

everything was working fine with a single Model, but now I am implementing more, I have noticed an issue.
I have several document Models which represent a different type of document. For now, let's say I have DocumentA and DocumentB.
Each Document allows file uploads, so I have created a FileUpload Model. A Document can have many FileUploads.
So, seems pretty straight forward at this point. My FileUpload table has a documentId field, which is a reference to the id field of the Document that is using it.
In DocumentA, I have something like so
public function uploadFile()
{
return $this->hasMany('App\UploadFile', 'documentId');
}
So DocumentA can have many UploadFiles, linked by the documentId.
DocumentB has the same function within its Model.
My problem lies with the UploadFiles model. Firstly, this model now has two belongTo events e.g.
public function documentA()
{
return $this->belongsTo('App\DocumentA', 'documentId');
}
public function documentB()
{
return $this->belongsTo('App\DocumentB', 'documentId');
}
This could be the problem, not sure if I can have multiple belongs to? My immediate problem however is to do with the migration of the doc_file table. At the moment I have this
Schema::table('doc_file', function (Blueprint $table) {
$table->integer('documentId')->unsigned()->default(0);
$table->foreign('documentId')->references('id')->on('document_a')->onDelete('cascade');
});
Schema::table('doc_file', function (Blueprint $table) {
$table->integer('documentId')->unsigned()->default(0);
$table->foreign('documentId')->references('id')->on('document_b')->onDelete('cascade');
});
So I am trying to provide foreign keys to my documents. When I try to migrate, it tells me that
Column already exists: 1060 Duplicate column name documentId
Am I handling my relationships correctly? Essentially, I have many documents, and each document can have many files.
Any assistance with my database relationships appreciated.
Many thanks
Looking at your problem at first glance, it seems that there is a little confusion for you regarding the concept model.
The Model Concept
A model is in fact a conceptualization of a real-world object as it is used to represent a real-world entity.
In other words, it represents a whole class of objects with similar properties. For instance a Car model would represent all cars, whether they are of type Lamborghini or Mercedez. The fact is that they all come under the Car classification.
Same concept goes in Eloquent, and with your use case; therefore a Document model is sufficient to represent both of your documents (DocumentA and DocumentB).
Eloquent Relationships
To refine what you've achieved so far, your models' relationships can be refactored as such:
Document Model
public function fileUploads(){
return $this->hasMany('App\FileUpload');
}
FileUpload Model
public function document(){
return $this->belongsTo('App\Document');
}
Based on the relationship "EACH document has MANY file uploads", and the inverse "EACH file upload BELONGS to exactly one document", as you can see, there is only one belongsTo() method in the FileUpload model to define the latter part of the relationship.
Similarly, the schema for the tables defining the above relationship are as follows:
// Schema for Document table
Schema::table('document', function (Blueprint $table) {
$table->increment('id');
$table->string('name', 100);
});
// Schema for FileUpload table
Schema::table('doc_file', function (Blueprint $table) { // file_uploads would have been a more friendly name in my opinion
$table->integer('documentId')->unsigned()->default(0); // note that `documentId` is interpreted as `documentid` in MySQL
$table->foreign('documentId')->references('id')->on('document')->onDelete('cascade');
});

Resources