kiwibg
kiwibg

Reputation: 334

Laravel: How to define belongsTo in a MorphPivot?

In my project there is a Many-to-Many polymorphic relationship (Many instances of a model called Package (morphedByMany) can contain many different content types (each MorphedToMany).

I've created a pivot table containing some additional fields that I'll need to access and query by, and so I've decided that the best thing would be to create a Pivot model by extending the MorphPivot.

Querying is now easy enough, however, I can't access the content through a relation (which I can do if i query the App\Packages::findOrFail(1)->contentType()). I know I should declare that the pivot belongsTo the contentType, but I'm not sure how to go about it seeing as it could belong to any of the morphed contentTypes.

EDIT Code blocks as requested

Content1

class Song extends Model
{

  public function packages()
  {
      return $this->morphToMany('App\Package', 'packageable')->withPivot('choice')->using('App\PackageContent');
  }

Content2

class Video extends Model
{

  public function packages()
  {
      return $this->morphToMany('App\Package', 'packageable')->withPivot('choice')->using('App\PackageContent');
  }

Package

class Package extends Model
{
  public function songs()
  {
      return $this->morphedByMany('App\Song', 'packageable')->withPivot('choice')->using('App\PackageContent');
  }

  public function videos()
  {
      return $this->morphedByMany('App\Video', 'packageable')->withPivot('choice')->using('App\PackageContent');
  }

MorphPivot

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphPivot;

class PackageContent extends MorphPivot
{
  protected $table = 'packageables';

Pivot table migration

    public function up()
    {
      Schema::create('packageables', function (Blueprint $table) {
        $table->integer('package_id');
        $table->integer('packageable_id');
        $table->string('packageable_type');
        $table->integer('choice');
      });
    }

Upvotes: 3

Views: 1628

Answers (1)

Jan Misker
Jan Misker

Reputation: 2149

I know it's been a couple of years, but maybe someone stumbles here. I had the same problem and solved it like this:

class PackageContent extends MorphPivot
{
  protected $table = 'packageables';

  public function package()
  {
    // regular belongs to
    return $this->belongsTo(Package::class); 
  }

  public function packageable()
  {
    // one to one morph, can also be named different
    return $this->morphTo(); 
  }
}

Upvotes: 1

Related Questions