0

I want to access a db field inside a relationship table. The (below) shown model has the field "type_id".

// The query (so far):
$page = Page::where('slug', $slug)
    ->with(['page_content' => function ($query) {
        return $query->with('content')
            ->orderBy('order')
            ->get();
    }])
    ->first();


// Model / Relationship
public function content()
{
    if ($this->type_id == 1) {
        return $this->hasMany(TypeOne::class, 'id', 'content_id');
    }

    if ($this->type_id == 2) {
        return $this->hasMany(TypeTwo::class, 'id', 'content_id');
    }
}

$this does provide the model structure, but there's no data in it. Is this even possible?

Chriss
  • 37
  • 4

1 Answers1

1

You can't access these values in the model.

About the polymorphic sql you can read more about it here

I advise you to create a property for each table.

Your Pages migration

Schema::create('pages', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('type_one_id');
    $table->unsignedBigInteger('type_two_id');
    /* ... */
    $table->foreign('type_one_id')
            ->references('id')->on('type_one')
            ->onDelete('cascade');
    $table->foreign('type_two_id')
            ->references('id')->on('type_two')
            ->onDelete('cascade');
});

Your App\Pages.php model

public function typeOneContents()
{
    return $this->hasMany('App\TypeOne');
}

public function typeTwoContents()
{
    return $this->hasMany('App\TypeTwos');
}

Your PagesController.php

$page = Page::where('slug', $slug)
    ->with(['page_content' => function ($query) {
        return $query->with(['typeOneContents', 'typeTwoContents'])
            ->orderBy('order')
            ->get();
    }])
    ->first();
Thiago Valente
  • 673
  • 8
  • 25