php - Laravel - Eager Load Single Item in a ManyToMany Realtionship -


in laravel, possible eager load 'first' item belongstomany relationship? in, return item relationship, rather collection?

from i've tried (and read) applying first() or limit('1') or other constraint not return individual item

use accessor.

i guess need latest, first, or such kind of single item collection, can this:

public function items() {   return $this->belongstomany(item::class); }  public function getlatestitemattribute() {   return $this->items->sortbydesc('created_at')->first(); } 

then can use:

$yourmodel->latestitem; // single related model or null 

edit: mentioned @hkan in comment, above code result in fetching whole collection , working on it. said, can use alternatively relation object , directly query table:

public function getlatestitemattribute() {   return $this->items()->latest()->first(); } 

however, way run query whenever call $model->latestitem. result new copy of model, not same instance, , can query database arbitrary number of times, depending on use-case.

the hard, best way mimic relationship:

public function getlatestitemattribute() {   if (!$this->relationloaded('latestitem')) {     $this->setrelation('latestitem', $this->items()->latest()->first());   }    return $this->getrelation('latestitem'); } 

in case $model->latestitem treated other single relationship, once loaded. is, single instance whenever call accessor , saved when using push method.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -