如何获取用户的评论?未找到列错误

时间:2018-05-08 15:20:35

标签: laravel

我有一个具有index()方法的UserController,该方法应该在用户的帖子中获取所有过去的评论,并且每个评论都会获得帖子详细信息(标题和日期)。所以我有下面的代码来获取用户过去的评论:

$pastComments = $user->comments()->with('post')->where('create_date', '<', now())->get();

create_date是posts表的一个字段,而不是comments表。

但这似乎是一个错误:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'create_date' in 'where clause' (SQL: select * from `comments` where `comments`.`user_id` = 1 and `comments`.`user_id` is not null and `create_date` < 2018-05-08 15:04:47)".

你知道为什么吗?

型号:

class User extends Authenticatable
{
    public function posts(){
        return $this->hasMany('App\Post', 'user_id');
    }
    public function comments(){
        return $this->hasMany('App\Comment','user_id');
    }
}

class Comment extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
    public function post(){
        return $this->belongsTo('App\Post');
    }

}


class Post extends Model
{
    public function admin(){
        return $this->belongsTo('App\User', 'user_id');
    }
    public function comments(){
        return $this->hasMany('App\Comment', 'post_id');
    }
}

表格结构:

Users table: id, name, ...
Comments table: id, post_id, user_id, ...
Posts table: id, name, user_id, ...

使用:

$comments = $user->comments()->with('post')->whereHas(['post' => function ($query) {$query->where('create_date', '<', now()); }])->get();

看来:

  strpos() expects parameter 1 to be string, array given

2 个答案:

答案 0 :(得分:1)

如果您想根据关系确定查询的范围,则需要使用whereHas,例如

$pastComments = $user->comments()->with('post')
        ->whereHas('posts', function ($query) {
            $query->where('create_date', '<', now());
        })
        ->get();

https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence

答案 1 :(得分:1)

Constraining Eager Loads

$pastComments = $user->comments()->with(['post' => function ($query) {
    $query->where('create_date', '<', now());
}])->get();