taylorotwell/eloquent — Issue #14: has_and_belongs_to_many doesn't work with table prefixes
Author: kmstrong
Created: 2012-02-11 21:34:58+00:00
State: open

Hi,

I'm working on a site that is using the table prefix in the db connection settings, and I ran into some issues using the has_and_belongs_to_many relationships.

For example, if you have models for users and roles and the User model has a relationship like so:

```
public function roles()
{
return $this->has_and_belongs_to_many('Role');
}
```

Then when you call something like `Auth::user()->roles`, it will throw an error like:

```SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'roles'```

I found a workaround by changing the return statement at the end of the has_and_belongs_to_many function to something like this:

```
$query = static::query($model);
$prefix = isset($query->query->connection->config['prefix']) ? $query->query->connection->config['prefix'] : '';

return $query
->select(array($prefix.static::table($model).'.*', $prefix.$this->relating_table.'.'.$this->relating_key))
->join($this->relating_table, $prefix.static::table($model).'.'.static::pk($model), '=', $prefix.$this->relating_table.'.'.$associated_key)
->where($prefix.$this->relating_table.'.'.$this->relating_key, '=', $this->{static::$primary_key});
```

I'm not sure if this is the most elegant solution since I'm not super familiar with how Eloquent works with the Query builder/Grammar classes, but it fixed the problem on my end.