【问题标题】:Unable to fetch data in Elequent Polymorphic Relationship无法在 Eloquent 多态关系中获取数据
【发布时间】:2016-09-17 11:25:29
【问题描述】:

我正在使用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);

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

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
        )

)

为什么这里缺少 cmets 实体?谢谢:)

【问题讨论】:

    标签: php mysql laravel-5 laravel-5.3


    【解决方案1】:

    尝试Eager loading,如下所示:

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

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

    commentable_type 列是 ORM 在访问可评论关系时如何确定要返回的拥有模型的“类型”。

    也请关注naming convention for models

    【讨论】:

    • 感谢您的回复!它仍然返回一个空值。 print_r($pin-&gt;replies-&gt;toArray()) outputs empty array
    • 尝试 dd($pin) 并检查 'cmets' 属性是否显示?
    • 我从头开始重新做了所有事情,并将 cmets 实体重命名为我的项目中的回复,尽管一切都保持不变。使用dd($pin) 它表明“回复”又名“cmets”属性为空http://i.imgur.com/K8iMJkT.png
    • 在您的 commentable_type 列值中使用 App\Posts 而不是 Posts,然后再次检查。
    • 我已经更新了答案,如果以后有人需要的话。并感谢您的支持并使其被接受。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 2021-12-09
    • 2021-12-07
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多