Is it possible to map relation's field directly on the model without writing a lot of code?
Let me give you an example:
class User extends Model
{
public function profile()
{
return $this->hasOne(UserProfile::class);
}
}
class UserProfile extends Model
{
public $fillable = ['first_name', 'last_name', 'address', 'phone', 'birth_on'];
}
Now I can do $user->profile()->first_name; but I want to know if it's possible to do $user->first_name. So map any fields on the UserProfile entity into my user model.
@RomainLanz That was quick :) I was going to show an example, but I don't think it's necessary anymore. Anyway, I suppose I wouldn't go with static property.
protected $mappedAttributes = [
'profile' => ['first_name', ...];
// or
// 'first_name' => 'profile.first_name'
];
public function __get($key)
{
if ($this->isMappedAttribute($key)) {
return $this->getMappedAttribute($key);
}
return parent::__get($key);
}
Not static in order to make it customizable and consistent with other eloquent features.
And you're making assumption that you can relay only single relation. Maybe you would like more? user->picture_path -> user->profile->picture->path?
@RomainLanz The logic goes in the isMappedAttribute and getMappedValue, so you can use either profile.first_name or profile => ['first_name, .. ] notation.
@RomainLanz Since it is custom behaviour I would rather want it (as a developer who defines it in my model) to run before the default behaviour, so yes, before the parent::__get($key)
@JarekTkaczyk That could be a good new feature to add on the next release of the plugin (user->picture_path -> user->profile->picture->path).
If we look at your $mappedFields array, I need to iterate over each relation to know if the field is mapped. I think that it's better to keep my definition.
@JarekTkaczyk Hey great package, but I have encountered not really a problem but a bug of sorts. Frankly I don't even know how to define it. But it goes as follows.
The mapping works great when directly called on in the view eg. $client->first_name which is a mapped to a "morphOne" relationship on a People model.
But when trying to combine this with the "Illuminate\Html" package's form model binding method it just doesn't work. I still have to define a accessor before it populates the field. Any suggestions?
@Curdal 99% that the reason for this is isset check that is called during form model binding. Please post relevant example in the github and I'll look into it tonight.