Return parents and childs from model
I have a model "Node". A node may have many childs and many parents.
So, the tables look like this
table nodes
id | name | created_at | updated_at
1 | Node A | .. | ..
2 | Node B | .. | ..
3 | Node C | .. | ..
4 | Node D | .. | ..
table nodes_relations
id | nodes_id | relation_nodes_id | created_at | updated_at
1 | 2 | 1 | .. | ..
1 | 3 | 1 | .. | ..
1 | 4 | 2 | .. | ..
Briefly:
- Node A has 0 parents and 2 childs (node B and node C)
- Node B has 1 parent (node A) and 1 child (node D)
- Node C has 1 parent (node A) and 0 childs
- Node D has 1 parent (Node B) and 0 childs
In my Node class, I have defined the following relation:
public function parents()
{
return $this->hasMany('App\NodesRelations','nodes_id');
}
public function children()
{
return $this->hasMany('App\NodesRelations', 'relation_nodes_id');
}
And this is the class NodeRelation:
class NodesRelations extends Model
{
//
public function parent()
{
return $this->belongsTo('App\Nodes', 'relation_nodes_id');
}
public function self()
{
return $this->belongsTo('App\Nodes', 'nodes_id');
}
}
I have a simple view to test the response:
$node = App\Nodes::with('parents','parents.self','children','children.self')->findOrFail($node_id);
echo $node;
The problem is that I do see the children with a the needed info (name for instance), when $node_id = 1, but parents is null when i query $node_id = 2.
Can somebody point me in the right direction? I have been struggling about this for hours now. Thanks in advance.
Ok, I figured it out. For those who are struggling with the same problem (or something similar).
It was pretty easy actually.
public function parentNodes()
{
return $this->belongsToMany('App\Node', 'nodes_relations', 'nodes_id', 'relation_nodes_id');
}
public function childNodes()
{
return $this->belongsToMany('App\Node', 'nodes_relations', 'relation_nodes_id', 'nodes_id');
}
That's it!
Please or to participate in this conversation.