Laravel 5.6 Create multiple relationships

Viewed 170

Hi I have a complex question. I have been working with Laravel for only a week. And I try to build price lists for customers.

I have 5 tables:

price_lists:
  id
  title

---------------------------
price_lists_products:
  id
  product_id
  price_lists_id
  price
  percent

---------------------------
price_lists_users:
  id
  user_id
  price_lists_id

---------------------------
products:
  id
  title
  price
---------------------------
users:
  id
  name

And I have to put them together like this:

There are a few price lists

Each price list is associated with products + price

Each user can associate up to 5 price lists

In product view and in the list, I need to show the user the product with the cheapest price that is set for him in the price lists

For example:

I have a book that belongs to 5 different price lists and each price list, a different price.

And there is a user associated with 3 price lists.

I want the user to get the cheapest price in the price lists to which he belongs

I hope this is understandable, I have no idea how to approach it, I would be happy if you can help me with it, thanks!

1 Answers

Create models for Product, PriceList and User.

In your Product model, create a many-to-many relationship to get related PriceList collection:

public function pricelists()
    {
        return $this->belongsToMany('App\PriceList')->withPivot('price', 'percent');
    }

In your PriceList model, create a many-to-many relationship to get related User collection:

public function users()
    {
        return $this->belongsToMany('App\User');
    }

Again in the Product model, you can get the cheapest price like so:

// get the cheapest listing by user_id, you can set default to logged in user
public function cheapestprice($user_id){
    $this->pricelists->whereHas('users', function ($query) {
        $query->where('user_id', $user_id);
    })->orderBy('price_lists_products.price','ASC')->first()->price;
}

Finally, with a Product object, you can get the cheapest price:

Product::first()->cheapestprice(Auth::user()->id);
Related