drtppp75155 2019-04-25 07:55
浏览 20

访问函数中的调用关系

I want to call relation into accessors function with less query

ticket has many messages ticket model has accessors function I want into accessors function if ticket->messages()->exist() == TRUE returns messages body, or ** if ticket->messages()->exist() == TRUE** returns tickets body this line code ($ticket->last_body) in view make one Query for each row and i want to decrease my query

Ticket model:

class Ticket extends Model
{

    public function messages()
    {
        return $this->hasMany(TicketMessage::class, 'ticket_id');
    }

    public function getLastBodyAttribute()
    {

        if($this->messages()->exists()){
            return $this->messages()->orderByDesc('created_at')->first()->body;
        } else {
            return $this->body;
        }
    }
}

Ticket massage belongsto tickets

TicketMessage model :

class TicketMessage extends Model
{
    public function ticket()
    {
        return $this->belongsTo(Ticket::class,'ticket_id');
    }
}

I get tickets with own relationships and passed to view TicketController:

class TicketController extends Controller
{
    public function index(Request $request)
    {
        $tickets = Ticket::with('messages')
                        ->where('status', 'open')
                        ->get();

        return view('ticket::supporter.supporter', compact('tickets'));
    }
}
this line code $ticket->last_body make one Query for each row and i want to decrease my query 

**supporter.blade** :

    @foreach($tickets as $ticket)
        <a href="{{url(Route('show_client_ticket', ['id' => $ticket->id]))}}">   
            {{$ticket->subject}} 
        </a>

        <p style="color: #959A9D;">
            {{$ticket->last_body}} //this line returns too much  Query
        </p>
        <hr>
    @endforeach
  • 写回答

1条回答 默认 最新

  • dpklt4291 2019-04-25 08:46
    关注

    Try to change this.

     public function ticket()
        {
            return $this->belongsTo(Ticket::class,'ticket_id');
        }
    

    to this.

     public function ticket()
        {
            return $this->belongsTo(Ticket::class,'id');
        }
    

    because the default primary key of the model is "id".

    or if you want to change the primary key. try this:

    class Ticket extends Model
     {
      protected $primaryKey = 'ticket_id';
    
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?