
[英]Get the DISTINCT id of users and find the MAX of their column then UPDATE, 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.