tareq1988 / wp-eloquent

Eloquent ORM for WordPress
https://tareq.co/2015/05/eloquent-orm-in-wordpress/
566 stars 135 forks source link

Auto-prefix doesn't work on selects, but does on insert. #63

Open fryiee opened 5 years ago

fryiee commented 5 years ago

As title. Example here (prefix is wp):

$supportCategory = SupportCategory::where('category_number', $row['Support Category Number'])->first();

var_dump($this->table); shows support_categories

$supportCategory = SupportCategory::create([
                "category_name" => $row["Support Category Name"],
                "category_number" => $row["Support Category Number"]
            ]);

var_dump($this->table); shows wp_support_categories

fryiee commented 5 years ago

Using the following getTable as a workaround:

public function getTable()
    {
        if(isset($this->table)) {
            $prefix =  $this->getConnection()->db->prefix;
            return substr($this->table, 0, strlen($prefix)) === $prefix ? $this->table : $prefix . $this->table;
        }

        return parent::getTable();
    }
cdwieber commented 5 years ago

I had a similar issue with updating existing models. I narrowed it down to Model.php:400 - $model->setTable($this->getTable());.

By the time it gets here, many times the table has already been prefixed, and it hits this two additional times. So for a save method it was trying to write the query for local.wp_wp_wp_appointments. @fryiee 's workaround has resolved this for me for the time being, but when I get some time I'd like to investigate further and see if I can't come up with a permanent fix. I'll make a PR if so.