Skip to content

Instantly share code, notes, and snippets.

@jonahgeorge
Last active November 15, 2016 00:24
Show Gist options
  • Save jonahgeorge/6d303a89ee05b0c3685bdae91cb88b42 to your computer and use it in GitHub Desktop.
Save jonahgeorge/6d303a89ee05b0c3685bdae91cb88b42 to your computer and use it in GitHub Desktop.

It seems that the Mappable trait only exposes additional getters/setters for the mapped columns. Is there any intention to make this trait behavior similar to laravel/framework #8200 where the "bad" column name is actually removed as a getter/setter?

Example:

MariaDB> describe cities;
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| region        | varchar(5)       | NO   |     | NULL    |                |
| region_id     | int(11)          | NO   |     | NULL    |                |
| name          | varchar(100)     | NO   |     | NULL    |                |

MariaDB> select * from cities;
+----+--------+-----------+-----------------+
| id | region | region_id | name            |
+----+--------+-----------+-----------------+
|  1 | NY     |         1 | New York        |
|  2 | NY     |         1 | Brooklyn        |

MariaDB> describe regions;
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| name          | varchar(100)     | NO   |     | NULL    |                |

MariaDB> select * from regions;
+----+------------------+
| id | name             |
+----+------------------+
|  1 | New York         |
class City extends Model
{
    use Eloquence, Mappable;

    public $timestamps = false;
    protected $maps = [
        "region_name" => "region",
    ];
 
    public function region()
    {
        return $this->belongsTo(Region::class);
    }
}

echo City::with('region')->find(1)->toJson();
/*
{
    "id": 1,
    "region": {
        "id": 1,
        "name": "New York"
    },
    "region_id": 1,
    "name": "New York"
}
*/

echo City::with('region')->find(1)->region; 
/*
"NY"
*/

The first example behaves as I would expect; however, in the second example I would expect it to return a class of type Region. Instead it's finding the underlying getter and fetching the region name instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment