1

I have 2 table

Subscriptions Table

id char(36) | other column

Licenses Table

id bigint(20) | license_key (string) | subscription_id char(36)

Model Subscription.php

protected $with = ['licenses'];

public function licenses()
{
        return $this->hasMany('App\License', 'subscription_id');
}

Eager Loading work for mostly case, but subscription_id = 6e20af64-81e6-428e-b9db-52317d1e478e

subscription_id = 6e20af64-81e6-428e-b9db-52317d1e478e exist in Licenses Table

This is QueryLog:

array:2 [▼
  0 => array:3 [▼
    "query" => "select * from `subscriptions` where `subscriptions`.`id` = ? limit 1"
    "bindings" => array:1 [▼
      0 => "6e20af64-81e6-428e-b9db-52317d1e478e"
    ]
    "time" => 3.9
  ]
  1 => array:3 [▼
    "query" => "select * from `licenses` where `licenses`.`subscription_id` in (9223372036854775807)"
    "bindings" => []
    "time" => 4.73
  ]
]

Why it does not work with only this subscription_id?

my env:

"laravel/framework": "6.20.17",

php: 7.4.14
anhduc.bkhn
  • 695
  • 3
  • 10
  • 21
  • did you try with: return $this->hasMany(License::class, 'foreign_key', 'local_key'); ? – Mariano Mar 03 '21 at 10:51
  • 1
    as it says, `// In Laravel 6.0+ make sure to also set $keyType protected $keyType = 'string';` – N69S Mar 03 '21 at 10:59

1 Answers1

1

As your primary key seems to be a UUID, you need to tell Laravel that your PK is a string. I use this very handy trait for this. Not only does it set the key type to string and disables incrementing the PK but also generates new UUIDs when creating new Models.

use Illuminate\Support\Str;

trait HasPrimaryUuid
{
    protected static function bootUsesPrimaryUuid()
    {
        static::creating(function ($model) {
            if (!$model->getKey()) {
                $model->{$model->getKeyName()} = (string)Str::uuid();
            }
        });
    }

    public function getIncrementing()
    {
        return false;
    }

    public function getKeyType()
    {
        return 'string';
    }
}

Simply use this trait in your models like with other traits:

class MyModel extends Model {
    use HasPrimaryUuid;
    
    // ...

}
Timo Schwarzer
  • 399
  • 4
  • 17