无法在雄辩的多态关系中获取数据

Unable to fetch data in Elequent Polymorphic Relationship

我正在使用 polymorphic relations 构建评论系统,看起来一切正常。

这是我的帖子模型

<?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');
    }

}

这是我的评论模型

<?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');
    }

}

现在的问题是,

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

没有 returning 任何与 post 相关的评论!请注意,它有作者实体但没有评论。

print_r($pin->toArray());

只会return下面的数组,

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
        )

)

为什么此处缺少 评论 实体?谢谢:)

尝试 Eager loading 如下:

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

并在数据库的 commentable_type 列中使用 App\Posts 而不是 Posts。那是因为:(引用自laravel documentation

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

另请关注naming convention for models