Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

eloquent - Laravel 8.X select all record with latest status

I have 2 model in relationship

Tickets model

public function status(){ return $this->hasMany(Status::class); }
public function latestStatus(){ return $this->hasOne(Status::class)->latest();}

Status model

public function tickets(){ $this->belongsTo(Ticket::class);}

I am trying to get the latest status of each tickets using this code

public function scopeFilteredStatus($query){ 
 return $query->whereHas('latestStatus',function($status){ 
  $status->whereIn('status', ['status1,'status3','status6']);
})->get(); }

what ive got

IlluminateDatabaseEloquentCollection {#1609 ▼
  #items: array:302 [?]
}

was expecting a fewer result

id --- user_id --- ticket_id --- status --- created_at
xx --- 10001   --- 3100      --- status1 --- 2020-01-13
xx --- 10001   --- 3200      --- status3 --- 2020-01-09
xx --- 10004   --- 2900      --- status6 --- 2020-01-20
and more...
question from:https://stackoverflow.com/questions/65896184/laravel-8-x-select-all-record-with-latest-status

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

remove get() in your scope:

public function scopeFilteredStatus($query){ 
 return $query->whereHas('latestStatus',function($status){ 
  $status->whereIn('status', ['status1,'status3','status6']);
})->get(); }

to

public function scopeFilteredStatus($query){ 
 return $query->whereHas('latestStatus',function($status){ 
  $status->whereIn('status', ['status1,'status3','status6']);
}) }

now try this: Ticket::filteredStatus()->get()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...