rakibtg rakibtg - 1 year ago 76
MySQL Question

Unable to fetch data in Elequent Polymorphic Relationship

I was building a commenting system using the polymorphic relations, it seems like everything works without any issue.
enter image description here

Here is my Posts Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
public $primaryKey = 'pid';
public $timestamps = false;

public function author()
{
return $this->belongsTo('App\User', 'p_author_id');
}

public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}

}


Here is my Comment Model

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}

public function user()
{
return $this->belongsTo('App\User');
}

public function posts()
{
return $this->belongsTo('App\Posts', 'pid');
}

}


Now the problem is,

$pin = Posts::find($pin_id);


is not returning any comments associated with the post! Note that it has the author entity but not the comments.

print_r($pin->toArray());


would only return the following array,

Array
(
[pid] => 17
[p_title] => Hello World?
[p_content] => How are you earth?
[p_author_id] => 4
[p_created_at] => 2016-09-15 17:18:16
[p_updated_at] => 2016-09-15 17:18:16
[comments_count] => 0
[votes] => 0
[author] => Array
(
[id] => 4
[name] => Human
[email] => human@mail.com
[created_at] => 2016-09-15 17:18:00
[updated_at] => 2016-09-15 17:20:05
)

)


why the comments entity is missing here? Thanks :)

Answer Source

Try Eager loading like following:

$pin = Posts::with('comments')->find($pin_id);

And use App\Posts instead of Posts in your commentable_type column in database. That's because: (Quoting from the laravel documentation)

The commentable_type column is how the ORM determines which "type" of owning model to return when accessing the commentable relation.

Also please follow the naming convention for models.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download