codeigniter-base-model
codeigniter-base-model copied to clipboard
Using with() across a chain of relationships
I was looking at doing something like this:
- town
- county
- country
town belongs to county, which belongs to country
doing town_model->with('county')->with('country)->get(xx)
it only gives me the direct relationship, i.e. county -- no nested relates callback happens for the county... am I missing something or is this a new feature request ?
MANY THANKS FOR EXCELLENT WORK! Find it much easier to deal with this than the bloat ware D2...
Just a quick and dirty fix that seems to have done the trick I was after:
if (in_array($relationship, $this->_with))
{
$this->load->model($options['model']);
foreach ( $this->_with as $r ) {
// Adding more _with to nest with this query
$this->{$options['model']}->with($r);
}
if (is_object($row))
I would not pretend its robust and bullet proof - but here you go - you can now improve it ;)
The syntax of the BaseModel seems to have changed try:
if (in_array($relationship, $this->_with))
{
$this->load->model($options['model'], $relationship . '_model');
foreach ( $this->_with as $r ) {
// Adding more _with to nest with this query
$this->{$relationship.'_model'}->with($r);
}
However i think some "with()s" can end up in the wrong hands (i.e.model ) The current syntax is made for gather stuff to one entry, not "nested_with()"
Just a little tweak if you have another relationships:
if (in_array($relationship, $this->_with)) { $this->load->model($options['model'], $relationship . '_model');
foreach ( $this->_with as $r ) {
if (strpos($r, '.')){
$parts = explode(".", $r);
$this->{$relationship.'_model'}->with($parts[1]);
}
}
if (is_object($row))
{
$row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
}
else
{
$row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
}
}
use:
->with('model.relation')...
Perhaps instead of changing with(), what about introducing with_all() or with_r(), recursive?
I recently looked at overriding with(), but realized that I did not always need the full recursion.
Hi kbjohnson90 , it's a good idea, I not always need the full recursion, it's why I use paths (model.relation)