webpatser/laravel-uuid

Many to many relationships

Gerungofulus opened this issue · 3 comments

Hey,

I have three entities: 'items', 'users', and 'cities'. Users can receive items in certain cities and I want to save where a particular user has received that item. As I could have millions of items in the database, I don't want to use integer ids, so I figured I'd use your uuids like so

Schema::create('items', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('name');
            $table->timestamps();
            $table->primary('id');
        });
Schema::create('item_user', function (Blueprint $table) {
            $table->increments('id');
            $table->uuid('item_id')->references('id')->on('items');
            $table->integer('user_id')->references('id')->on('users');
            $table->integer('city_id')->nullable();
            $table->timestamps();
        });
Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('country_id');
            $table->string('englName');
            $table->string('nativeName');
            $table->timestamps();
        });

and added the following lines in the Item Model class

public static function boot()
  {
    parent::boot();
    self::creating(function ($model) {
        $model->id = (string) Uuid::generate(4);
    });
  }
    public function users(){
      return $this->belongsToMany('App\User');
    }

    public function cities(){
      return $this->belongsToMany('App\City', 'item_user');

However the relationships weren't returning anything even though I filled the database with legitimate testing data. So I started investigating and just put a var_dump on all queries using \DB::connection()->enableQueryLog(); and {{var_dump(DB::getQueryLog())}} finding that the binding for those queries goes wrong. As you can see it uses some integer value even though it should be using the uuid. Do you have any ideas what is going wrong?

[3]=> array(3) { ["query"]=> string(283) "select "users".*, "item_user"."item_id" as "pivot_ item_id", "item_user"."user_id" as "pivot_user_id" from "users" inner join "item_user" on "users"."id" = "item_user"."user_id" where "item_user"."item_id" in (?)" ["bindings"]=> array(1) { [0]=> int(1) } 
nymo commented

Did you set in your models the following class member variables?

public $incrementing = false;
public $keyType = 'string';

thank you so much, that solved my problem. I didn't find anything about this before your reply!

@Gerungofulus you created a model ItemUser.php ?