我有模型票,用户可以在其中解释问题。
Ticket.php
class Ticket extends Model
{
protected $table = 'tickets';
/**
* @var array
*/
protected $guarded = [];
/**
* @var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function ticket_replies()
{
return $this->hasMany(TicketReply::class, 'ticket_id');
}
public function ticket_assigned_agents()
{
return $this->hasMany(TicketAssignedAgent::class, 'ticket_id');
}
}
还有另一种模式 TicketReply.php
class TicketReply extends Model
{
protected $table = 'ticket_replies';
/**
* @var array
*/
protected $guarded = [];
/**
* @var array
*/
protected $hidden = [
'created_at', 'updated_at'
];
public function staffs(){
return $this->belongsTo(Staff::class,'user_id');
}
public function ticket()
{
return $this->belongsTo(Ticket::class, 'ticket_id');
}
}
现在我想从票证回复中获取工作人员姓名
查询
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with('ticket_replies')->first();
return response()->json($ticket);
}
我想通过ajax成功从TicketReply模型获取人员姓名。
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}
但是它不起作用。我该怎么办?
答案 0 :(得分:1)
渴望加载嵌套关系
public function getReplies($ticket_id)
{
$ticket = Ticket::where('id',$ticket_id)->with(['ticket_replies','ticket_replies.staffs'])->first();
return response()->json($ticket);
}
然后执行与您相同的操作
$.each(ticket.ticket_replies, function(index, reply) {
console.log(reply.staffs.name);
}