php - 无法在 Eloquent 多态关系中获取数据

标签 php mysql laravel-5 laravel-5.3

我正在使用 polymorphic relations 构建一个评论系统,似乎一切正常,没有任何问题。 enter image description here

这是我的帖子模型

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

不会返回与帖子相关的任何评论!请注意,它有作者实体但没有评论。

print_r($pin->toArray());

只会返回以下数组,

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 .

关于php - 无法在 Eloquent 多态关系中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39546284/

相关文章:

php - 我想知道是否有一些通用文本 block 用于尝试 "break"输入,例如文本字段

php - MySQL:相同的值不相同

php - Eloquent Join - where 关闭

php - Laravel 验证器抛出异常而不是重定向回来

php - Magento - 从数据库手动将订单从 1.4 迁移到 1.7

php - 为什么只从我的数据库中获取 1 个表中的记录

javascript - PHP 验证代码不能工作年龄?

mysql - sails mysql : ER_NO_DB_ERROR: No database selected

mysql - 如何使用 MySql 根据时间间隔获取 id

php - Laravel 和 MySQL 的唯一 IP 计数器