Welcome Guest, Not a member yet? Register   Sign In
DMZ self relationship parent_id
#1

[eluser]timobg[/eluser]
Hi,

I am still a novice in CI and DMZ and am trying to make a self relationship in a model Page with parent field and:
relations: has_one and has_many

Should I use a dedicated table for the relations or not?

Code:
<?php

class Page extends DataMapper{
    
    
    public $table = 'pages';
    
    public $has_one = array('p'=>array('class'=>'page', 'other_field'=>'children'));
    public $has_many = array('children'=>array('class'=>'page', 'other_field'=>'p'));

in the DB table 'pages', there is a 'p_id' field for the parent id

In this case in the controller I am using

$data = $this->Page->where('id', 1)->children->get();

But it returns an empty array

Regards!
#2

[eluser]OES[/eluser]
You don't need to create a relationship table for parent.

Im not fully sure if this will work but worth a go.

class Page extends DataMapper {

$has_one = array(
'parent' => array(
'class' => 'page',

)
);
}
#3

[eluser]WanWizard[/eluser]
If it's a one-to-many relationship, it needs to be defined as
Code:
public $has_one = array(
    'p' => array(
        'class' => 'page',
        'other_field' => 'page'
    )
);

public $has_many = array(
    'page' => array(
        'other_field' => 'p'
    )
);

A page has one parent, and multiple child pages.

Then there's the way you query this. Your statement can never work, since no parent has been selected before you select children.

It has to be
Code:
// get the parent
$this->Page->get_by_id(1);
// get this parents child pages
$this->Page->page->get();

// or in one go
$this->Page->get_by_id(1)->page->get();
#4

[eluser]timobg[/eluser]
Hi,

I just had the chance to test now and it seems to be working. Thank you!

But I do not know what is the difference between ->where('id', 1) and ->get_by_id(1) ?
#5

[eluser]timobg[/eluser]
OK, never mind!

Code:
$this->Page->get_by_id(1)

and

Quote:$this->Page->where('id', 1)->get()

is the same!

Now I got it! Thank you!

Regards!




Theme © iAndrew 2016 - Forum software by © MyBB