Mohamed Mahfouz
Mohamed Mahfouz

Reputation: 241

Another incremental id for users' products

I have a users table and products table. Each user can have many products and everything goes fine with id in the products table. What I am trying to do is to add another incremental column in relation to users.

I am trying to not only have:

user[1] could have product id [1,5,7] ❌
user[2] could have product id [2,3,4] ❌

But also:

user[1] has product another_incrematal [1,2,3,4,5, ....] ✅
user[2] has product another_incrematal [1,2,3,4,5, ....] ✅

Are there any built-in methods in laravel that could do so?

Thanks in advance.

// User
public function products()
    {
        return $this->hasMany(Product::class);
    }

// Product
  public function user()
    {
        return $this->belongsTo(User::class);
    }

Upvotes: 0

Views: 47

Answers (1)

Zakalwe
Zakalwe

Reputation: 1622

You probably want to introduce an intermediate model to represent the relationship between a User and Product - UserProduct (or something better depending on your use-case) which has user_id, product_id and a third field of, say, index. A User hasMany UserProducts and a Product hasOne UserProduct As @TimLewis pointed out, you would have to generate index at the time of insertion by counting the products for a user and adding one.

//User
public function products() {
    return $this->hasManyThrough(Product::class, UserProduct::class)
}

//many ways to do this but one example is...
public function addProduct($product) {

    UserProduct::create([
        'user_id' => $this->id,
        'product_id' => $product_id
        'index' => $this->products()->count() + 1
    ]);

}

//Product
public function user() {
    return $this->hasOneThrough(User::class, UserProduct::class)
}

Upvotes: 1

Related Questions