繁体   English   中英

获取在 Laravel 中评论票证的用户的不同电子邮件

[英]Get distinct emails of users who commented on a ticket in Laravel

我有以下型号。

class Ticket extends Model
{
    protected $fillable = ['title', 'content', 'slug', 'status', 'user_id'];
    protected $guarded = ['id'];

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

    public function comments()
    {
        return $this->hasMany('App\Comment', 'post_id', 'id');
    }

    public function commenters()
    {
        return $this->hasManyThrough('App\User', 'App\Comment');
    }
}

评论

class Comment extends Model
{
    protected $guarded = ['id'];

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

    public function ticket()
    {
        return $this->belongsTo('App\Ticket', 'post_id', 'id');
    }

    public function post()
    {
        return $this->morphTo();
    }
}

用户

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    protected $guarded = ['id'];

    protected $hidden = [
        'password', 'remember_token',
    ];
}
  • 一张票有很多评论
  • 一条评论有一个用户

我正在尝试提取对票证发表评论但没有成功的用户的名称字符串列表。

在我的 controller 中,我使用以下代码来提取评论者列表。

Ticket::where('id', $comment->post_id)->commenters

但是,我收到了错误:

Eloquent 构建器实例上不存在属性 [commenters]。

你错过了一个闭包。 此查询未完成:

Ticket::where('id', $comment->post_id)

未完成的查询是Builder class 的实例,而不是您所期望的Ticket实例或Ticket实例的Collection

如果您期望单个Ticket实例,那么您将使用->first()

$ticket = Ticket::where('id', $comment->post_id)->with(['commenters'])->first();
$commenters = $ticket->commenters;

如果您期望多个Ticket实例,那么您将使用->get()

$tickets = Ticket::where('id', $comment->post_id)->with(['commenters'])->get();
foreach($tickets AS $ticket){
  $commenters = $ticket->commenters;
}

注意: ->with(['commenters'])用于加速->commenters的加载; 如果您省略它,那么当您尝试访问$ticket->commenters时会运行一个新查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM