【问题标题】:How to get nested relation record for ajax request in laravel?如何在laravel中获取ajax请求的嵌套关系记录?
【发布时间】:2020-12-06 12:58:35
【问题描述】:

我有用户解释问题的模型票。

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);
}

但它不起作用。我该怎么办?

【问题讨论】:

    标签: ajax laravel laravel-5 eloquent


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2017-12-04
      • 2019-09-08
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2016-09-26
      • 2022-11-23
      • 2020-04-04
      相关资源
      最近更新 更多