Skip to content

Instantly share code, notes, and snippets.

@wayneashleyberry
Created November 1, 2012 10:47
Show Gist options
  • Save wayneashleyberry/3993012 to your computer and use it in GitHub Desktop.
Save wayneashleyberry/3993012 to your computer and use it in GitHub Desktop.
key-value storage for eloquent models
<?php
namespace App;
// add key-value storage to models
class Eloquent extends \Eloquent {
protected $metaClass = 'ObjectMeta';
public function meta()
{
return $this->has_many($this->metaClass);
}
public function set_meta($key, $value)
{
$meta = $this->meta()->where('key', '=', $key)->first();
if ($meta)
{
$meta->value = $value;
$meta->save();
}
else
{
$metaClass = $this->metaClass;
$meta = new $metaClass(array(
'key' => $key,
'value' => $value
));
$this->meta()->insert($meta);
}
}
public function get_meta($key)
{
$meta = $this->meta()->where('key', '=', $key)->first();
if ($meta)
{
return $meta->value;
}
}
}
<?php
namespace App;
class ObjectMeta extends \Eloquent {
public static $key = 'key';
public static $table = 'object_meta';
}
<?php
$object = Object::find(1);
$object->set_meta('zef', 'side');
var_dump($object->get_meta('zef'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment