访问函数中的调用关系

时间:2019-04-25 07:55:12

标签: php laravel relationship accessor

我想用更少的查询将关系调用到访问器函数中

机票有很多讯息 票证模型具有访问者功能 我想进入访问器功能如果ticket-> messages()-> exist()== TRUE 返回消息s body, or ** if ticket->messages()->exist() == TRUE** returns ticket的正文 此行代码($ ticket-> last_body)在视图中为每一行进行一次查询,而我想减少查询

机票型号

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

门票按摩属于门票

TicketMessage模型

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

我得到具有自己关系的票证并传递给查看 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 个答案:

答案 0 :(得分:0)

尝试更改此内容。

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

对此。

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

因为模型的默认主键是“ id”。

,或者如果您想更改主键。试试这个:

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

...