Using polymorphic relationships in Eloquent to ext

2019-08-05 13:29发布

I am quite new to Slim, still trying to learn it and decided to redo an old app I'd made. I am trying to use Eloquent but have quickly gotten lost doing what I wouldn't think is very complicated. The app I had was even too complicated to learn on, so I backtracked to this tutorial here, as this is more or less what I am trying to do, use models extending one other class, to see if I can even get this working: http://www.richardbagshaw.co.uk/laravel-user-types-and-polymorphic-relationships/ It's just a user type extension.

I cannot. This is a tutorial for Laravel obviously, so I know it will be a bit different. I have recreated the database (minus some of the extraneous stuff like username and password) and populated it sufficiently. I have copied the code for the User, Freelancer and Employee classes, modifying only the User class removing the extra methods which don't seem to be required for this (I think) as below.

namespace eloquent\eloquent;

class User extends Eloquent implements {

  protected $table = 'users';

  public function userable()
  {
        return $this->morphTo();
  }
}

If I do this:

$user = $app->user->find(1)->firstName;
echo $user

It works as expected. This does not:

$user = $app->user->find(1);
echo $user->userable->dayrate;

It gives me this: Fatal error: Class 'Employee' not found in D:\Apache24\htdocs\eloquent\vendor\illuminate\database\Eloquent\Model.php on line 900

It does however correctly identify whether it's looking for an employee or a freelancer, which I assume is coming from the DB column userable_type.

Question is really how should I be accessing the fields of the subclass? Am I doing it totally wrong, or is there a better way?

1条回答
成全新的幸福
2楼-- · 2019-08-05 13:54

I eventually came back to this question, and was able to solve it, just in case anyone else is having a similar problem. The problem was that it was looking for the exact string in the Database as the usertype, in this case Employee. What it really needed, was to look for the whole string including the namespace. By adding the entire namespace into the database entry as userable_type (ie eloquent\eloquent\Employee) it then picks it up and can find the model... I looked into options in Eloquent, like MorphClass but that does not appear to do what I need.

I haven't actually implemented this into a project I'm working on yet, but I imagine I'll probably either leave the whole string in there because I'm lazy and it's not a mission-critical, time sensitive app, or try to do something with middleware or ??. Anyways, hope that helps someone else.

查看更多
登录 后发表回答