Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent best practice for key/value pair type table

My application is a CMS intended for websites for businesses. I have a table called business_info that looks like this:

id  | field         | value
-----------------------------------------
1   | name          | Testing Company
2   | official name | Testing Company LLC
3   | main_location | The Bay Area
4   | year          | 1999
5   | address       | 55 Street Rd
6   | suite         | Unit 5
7   | city          | Anytown
8   | state         | CA
9   | zip           | 55555
10  | tollfree      | 1(888) 555-5555

I don't think the current Eloquent model will work to efficiently manage this information, so I extended it and started working on a more useful model. I'd like to be able to do something like:

$business_info->zip = "66666";
$business_info->save();

This is what I have so far, but I'm not sure how to proceed:

class Business_Info extends Eloquent
{
    public static $table = 'business_info';

    public static function all()
    {
        $business_info_rows = with(new static)->query()->get();
        foreach ($business_info_rows as $business_info_row)
        {
            $business_info[$business_info_row->attributes['field']] = $business_info_row->attributes['value'];
        }
        return $business_info;
    }

    public function __set($key, $value)
    {

    }
}

Perhaps someone could offer some advice on how to proceed or perhaps another approach? Thanks!

like image 640
Yev Avatar asked Nov 03 '22 00:11

Yev


1 Answers

You're on the right track, especially with overriding the __set magic method. Basically, you'll want that method to look something like this for this specific model.

public function __set($key, $value)
{
    $this->set_attribute('field', $key);
    $this->set_attribute('value', $value);
}

That sets the field and the value columns to their respective values when you do something like $business_info->zip = "12345";

As for getting all the business information, do you really just want to return an array of data? I'd perhaps make a new method for doing that and leave all as it is. But what you've got looks fine to me.

like image 94
Jason Lewis Avatar answered Nov 07 '22 20:11

Jason Lewis