【问题标题】:Laravel eloquent-relationships does not work in my case [duplicate]Laravel 雄辩的关系在我的情况下不起作用[重复]
【发布时间】:2021-06-01 22:42:00
【问题描述】:

我有两张桌子

订阅表

id char(36) | other column

许可证表

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

模型订阅.php

protected $with = ['licenses'];

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

Eager Loading 适用于大多数情况,但 subscription_id = 6e20af64-81e6-428e-b9db-52317d1e478e

subscription_id = 6e20af64-81e6-428e-b9db-52317d1e478e 存在于许可证表中

这是查询日志:

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
  ]
]

为什么它不能只使用这个 subscription_id?

我的环境:

"laravel/framework": "6.20.17",

php: 7.4.14

【问题讨论】:

  • 你试过了吗:return $this->hasMany(License::class, 'foreign_key', 'local_key'); ?
  • 正如它所说,// In Laravel 6.0+ make sure to also set $keyType protected $keyType = 'string';

标签: php laravel eager-loading


【解决方案1】:

由于你的主键似乎是一个 UUID,你需要告诉 Laravel 你的 PK 是一个字符串。我为此使用了这个非常方便的特性。它不仅将密钥类型设置为string 并禁止增加 PK,而且还会在创建新模型时生成新的 UUID。

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';
    }
}

只需 use 在您的模型中使用此特征,就像使用其他特征一样:

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

}

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2019-08-13
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2019-06-07
    相关资源
    最近更新 更多