I have a Project
model. Each Project
can have a thumbnail, main image and other multiple assets / images (project details for example) and also multiple text contents (that would be placed in between these images). And each Project
page will pull in these assets (except the thumbnail) and texts, and display them in a specific order (that I define by drag and drop on my control panel).
So basically the similar structure to what Behance
uses for example. I'm trying to structure this using Eloquent and here is what I have so far:
I have models Image
Text
and Node
. Node
model's table has order
column to custom order these nodes.
My polymorphic relationships look like these:
MyProject
model:
public function nodes()
{
return $this->morphedByMany(Node::class, 'nodeable');
}
My Node
model:
public function nodeable()
{
return $this->morphTo();
}
Then in my code I do the following:
$project = new App\Project;
$project->title = 'Some title';
$project->save();
$image = new App\Image;
$image->source = 'somefile.jpg';
$project->nodes()->save($image);
But I get the following error:
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'project_id' in 'field list' (SQL: insert into `nodeables` (`nodeable_id`, `nodeable_type`, `project_id`) values (5, App\Node, 1))'
So I guess it's trying to create an entry inside a pivot table nodeables
. Then I created this table and it saved an entry inside the pivot table, but not inside nodes
table.
This is driving me mad! :(
Node is not been saved because your using the relationship to save an image model.There is no instance of a new Node object.
You need to define the relationships for Images and Texts in the Node model hence when it comes to saving you would use
$node = new App\Node;
$node->save($image);
$project->nodes()->save($node);
This will ideally save a node record in the database. However if the work of node is to only hold the order. Consider adding the field in the pivot table.