eloquent - Laravel 5 nested relationship -


i have 3 tables, with:

user: id | name products: id | name | user_id tracks: user_id | product_id 

relationships between these models (tables) are:

//user.php************************************************* public function products() {     return $this->hasmany('app\product'); } public function track() {     return $this->hasmany('app\track'); }   //product.php************************************************* public function user() {     return $this->belongsto('app\user'); } public function track() {     return $this->belongsto('app\track'); }   //track.php*************************************************  public function products() {     return $this->hasmany('app\product'); }  public function user() {     return $this->belongsto('app\user'); } 

track table used if user want track product. kind of bookmark.

so, when i'am on product page, $product = app\product::find(1), if want echo user name, $product->user()->name, if want know if user tracking current product, when $product->user()->track()->get() receive error:

call undefined method illuminate\database\query\builder::track() 

if $product->user()->with('track')->get(), don't error, user object not contain info if user tracking product.

how can know if user tracking product?

first, of relationship should these

product.php

public function track() {     return $this->hasmany('app\track'); } 

track.php

public function product() {     return $this->belongsto('app\product'); } 

now check if user tracking product

$product = app\product::find($id); $product->user->track()->where('product_id', $product->id)->first(); 

another way

$user = app\user::find($id); $user->track()->where('product_id', $product->id)->first(); 

and check if logged in user tracking product, can logged in user auth::user() , so

$user = auth::user(); $user->track()->where('product_id', $product->id)->first(); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -