简体   繁体   中英

Laravel 5, Eloquent relationship/ Method does not exist

I have 3 tables in laravel 5.6

First Table

//Table1> users: id | name
//and in Model: User
public function bookmarks()
{
   return $this->hasMany(Bookmark::class);
}

Second Table

//Table 3> bookmarks: user_id  | bookmarkable_id  | bookmarkable_type     
// and in Model: Bookmark
public function user()
{
    return $this->belongsTo(User::class);
}

public function products()
{
    return $this->morphedByMany('App\Product', 'bookmarkable');
}

Third Table

//Table3> products: id | title | user_id
//and in Model: Product
public function user()
{
    return $this->belongsTo(User::class);
}

public function bookmarks()
{
    return $this->morphToMany('App\Bookmark', 'bookmarkable');
}

Now, I want return all bookmarked products for current user:

$products = auth()->user()->bookmarks()->products()->latest()->paginate(18);

But I get this error:

"Method Illuminate\\Database\\Query\\Builder::products does not exist."

What is my wrong?

I believe the best to way to this is reverse your thinking a little bit. Go from the Product model (as you want a collection of products) and work your way back through the bookmarks with a whereHas which filters down by the current users ID.

$bookmarkedProducts = Product::whereHas('bookmarks', function($q) {
    $q->where('user_id', auth()->id());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM