php - Laravel simplify nested relation output -
i items owned authenticated user.
$items=auth::user()->with('items')->get();
in view can access items collection, instead of title_id want retrieve item_title value. i'm able item_title value using code below:
$item->title->title
is possible simplify retrieve title this: $item->title ?
here models , relations:
users id username item id user_id title_id item_titles id title
user model:
public function items() { return $this->hasmany('item', 'user_id', 'id'); }
item model:
public function user(){ return $this->belongsto('user', 'user_id', 'id'); } public function title() { return $this->belongsto('itemtitle','title_id','id'); }
itemtitle model:
public function item() { return $this->hasmany('item', 'title_id', 'id'); }
update
excuse me wasn't clear. precise - want find eloquent alternative to:
$items=item::where('user_id','=',auth::id())->leftjoin('item_titles', 'item.title_id', '=', 'item_titles.id')->get(); @foreach ($items $item) {{ $item->title }} @endforeach
just change relationship function to
item model:
public function title() { return $this->belongsto('itemtitle','title_id','id')->first()->title; }
you need call $item->title()
unless do
public function gettitleattribute(){ return $this->title(); }
you might funny stuff being called 'title' $item->title
should work think
Comments
Post a Comment