Skip to content

Commit e3ff880

Browse files
committed
Allow dot notition for getAttribute
1 parent 57722d2 commit e3ff880

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,52 @@ public function getTable()
195195
return parent::getTable();
196196
}
197197

198+
/**
199+
* Get an attribute from the model.
200+
*
201+
* @param string $key
202+
* @return mixed
203+
*/
204+
public function getAttribute($key)
205+
{
206+
// Check if the key is an array dot notation.
207+
if (strstr($key, '.'))
208+
{
209+
$attributes = array_dot($this->attributes);
210+
211+
if (array_key_exists($key, $attributes))
212+
{
213+
return $this->getAttributeValue($key);
214+
}
215+
}
216+
217+
return parent::getAttribute($key);
218+
}
219+
220+
/**
221+
* Get an attribute from the $attributes array.
222+
*
223+
* @param string $key
224+
* @return mixed
225+
*/
226+
protected function getAttributeFromArray($key)
227+
{
228+
if (array_key_exists($key, $this->attributes))
229+
{
230+
return $this->attributes[$key];
231+
}
232+
233+
else if (strstr($key, '.'))
234+
{
235+
$attributes = array_dot($this->attributes);
236+
237+
if (array_key_exists($key, $attributes))
238+
{
239+
return $attributes[$key];
240+
}
241+
}
242+
}
243+
198244
/**
199245
* Set a given attribute on the model.
200246
*

tests/ModelTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,4 +419,19 @@ public function testRaw()
419419
$this->assertTrue(is_array($result));
420420
}
421421

422+
public function testDotNotation()
423+
{
424+
$user = User::create(array(
425+
'name' => 'John Doe',
426+
'address' => [
427+
'city' => 'Paris',
428+
'country' => 'France',
429+
]
430+
));
431+
432+
$this->assertEquals('Paris', $user->getAttribute('address.city'));
433+
$this->assertEquals('Paris', $user['address.city']);
434+
$this->assertEquals('Paris', $user->{'address.city'});
435+
}
436+
422437
}

0 commit comments

Comments
 (0)