简体   繁体   中英

Polymorphic relations in Laravel 4 - morphOne()

Im having trouble creating a polymorphic relationship between two models:

  • Upload
  • Group

Simplified version of Group Model:

use Cartalyst\Sentry\Groups\Eloquent\Group as SentryGroupModel;

class Group extends SentryGroupModel {

  ...

  /**
   * returns the logo (upload model) from this agency
   *
   * @return Upload
   */
  public function logo()
  {
      return $this->morphOne('Upload', 'uploadable', 'model_type', 'model_id');
  }  

  ...

}

Simplified version of the Upload model

class Upload extends Eloquent {

  ...

  /**
   * returns the polymorphic relationship
   *
   * @return Upload
   */
  public function uploadable()
  {
      return $this->morphTo('uploadable', 'model_type', 'model_id');
  }  

  ...

}

As you can see the Group model is actually an extended Sentry 2 Group model, which is intern an extended Eloquent model.

When calling the relationship in a controller as such:

$agencyGroup->logo->saveUpload('logo');

i get the PHP error:

Call to a member function saveUpload() on a non-object

Any help with this?

The function logo() returns a MorphOne relationship and, since there's no method called saveUpload defined o MorphOne , it redirects the call to its Builder , which also doesn't have the method and throws the second exception you are experiencing:

Call to undefined method Illuminate\\Database\\Query\\Builder::saveUpload()

That behavior is expected and it's the way Eloquent works. That's why you should use just logo without () as you were trying in the first place.

Although, your $agencyGroup may not have a logo, which causes the NULL->saveUpload() I've mentioned and throws the first exception:

Call to a member function saveUpload() on a non-object

Try simply adding this on your controller:

if (empty($agencyGroup->logo)) {
    var_dump("There's no logo.");
    die();
}

$agencyGroup->logo->saveUpload('logo');

If you see the message "There's no logo", it means you should first create one logo before calling it's saveUpload method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM