【问题标题】:`Trying to get property of non-object` using `hasManyThrough` relationship laravel 5使用`hasManyThrough`关系laravel 5`尝试获取非对象的属性
【发布时间】:2015-06-03 08:03:54
【问题描述】:

我正在尝试使用Laravel 5 开发一个博客,我必须在帖子中与用户一起显示评论。

这是我的数据库表架构。

User

  • 身份证
  • 姓名

Posts

  • 身份证
  • post_content
  • user_id

Comments

  • 身份证
  • 评论
  • user_id
  • post_id

这是我的User Model

public function posts()
{
    return $this->hasMany('App\Models\Posts');
}

public function comments(){
    return $this->hasManyThrough('App\Models\Comments','App\Models\Posts');
}

这是我的Posts Model

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

    public function comments(){
        return $this->hasMany('Ap\Models\Comments');
    }  

这是我的Comment Model

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

    public function user(){
        return $this->posts->name;
    }

这是我如何访问user name的代码

$comments = Comments::find(1);
$comment['comment'] = $comments->comment;
$comment['user_name'] = $comments->name;
$comment['post_id'] = $comments->posts->id;

可能是我没有朝着正确的方向前进?如果我做得对,那么为什么它不起作用。

【问题讨论】:

  • 您的模型在 App\Model 命名空间中吗?默认只是应用程序...
  • @Gregory 是的,我的模型在 App\Models 命名空间中,我刚刚修改了一点。

标签: php eloquent laravel-5 has-many-through


【解决方案1】:

在 laravel 5 中,您不会像现在那样调用模型。由于模型存储在 app 文件夹中,因此只需调用即可。另外,我认为您需要定义关系

class User extends Model {

    public function phone()
    {
        return $this->hasOne('App\Phone');
    }

}

class Phone extends Model {

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

}

$phone = Phone::find(1);

对于外键和更多关于 laravel 5 中 Eloquent 关系的情况,只需遵循 laravel 网站上的文档即可。确保查看 eloquent 允许的动态属性

http://laravel.com/docs/5.0/eloquent

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2020-09-28
    • 2018-02-10
    相关资源
    最近更新 更多