Eloquent 模型 hasOne 返回一个不相关的模型

Eloquent model hasOne returning a non related model

背景资料

在我的项目中,我使用了 Illuminate\Database 包。

我设置了两个 类:User 和 Customtag。我正在尝试建立两者之间的关系。

我有两个表:vip_users 和 vip_customtags。两者都有一个名为 'steamid' 的列,它是 VARCHAR(255).

现在,有多个用户,但对于这种情况:我有一个 steamid 为 76561198048535340 的用户。

并且有一个 steamid 为 76561198048535341

的自定义标签

问题

foreach (User::all() as $u)
{
    echo "User: " . $u->vip_id . "<br>";
    print_r($u->customtag);
}

此代码打印用户 1、2、3、4、5...等。但是当 steamid 为 76561198048535340 的用户出现时,它 returns steamid 为 76561198048535341 的自定义标签

User: 1
User: 2
VipSystem\Models\Customtag Object
(
...
    [attributes:protected] => Array
        (
            [steamid] => 76561198048535341
        )

    [original:protected] => Array
        (
            [steamid] => 76561198048535341

        )
...
)
User: 3
User: 4
User: 5

反过来,请求所有自定义标签也能正常工作。例如:

foreach (Customtag::all() as $tag)
{
    echo "Tag: " . $tag->id . "<br>";
    print_r($tag->user);
}

打印:

Tag: 1
Tag: 2
Tag: 3
Tag: 4
Tag: 5

用户

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Model
{
    public $timestamps = false;
    public $primaryKey = "steamid";

    public function customtag(): HasOne
    {
        return $this->hasOne(Customtag::class, "steamid", "steamid");
    }
}

自定义标签

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Customtag extends Model
{

    public $timestamps = false;
    public $primaryKey = "id";

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, "steamid", "steamid");
    }
}
/**
 * @return Customtag
 *
 * @throws ModelNotFoundException
 */
public function customtag()
{
    return Customtag::where('steamid', '=', '' . $this->steamid)->get()->firstOrFail();
}

强制将 steamid 变成字符串似乎对我有用。 SQL 正在用一个整数执行。

默认情况下,Laravel classes 期望主键是一个递增的整数。你需要告诉 class 主键实际上是一个字符串。

将以下内容添加到您的 User class:

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