Laravel:关系有问题吗? [英] Laravel: Issue with relationship?
问题描述
我开始思考为什么Laravel会实现与他们框架的关系,他们从来没有为我工作过,而且他们承受巨大的压力以至于在破裂时必须加以修复.这是我的关系第五次返回空值,即使确保我已正确设置它们也是如此?
I'm beginning to think why did Laravel implement relationships to their framework, they've never worked for me and their a huge stress to fix when they break. This is the 5th time my relationships are returning null, even when ensuring I've set them up properly?
class UserStats extends Authenticatable
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function user()
{
return $this->belongsTo(User::class, 'id');
}
}
还有
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stats() {
return $this->belongsTo(UserStats::class, 'user_id');
}
}
尽管,在致电
{{ $user->stats->some_column }}
stats
返回null ... $user
不是null.
stats
is returning null... $user
isn't null.
推荐答案
以下是我注意到的有关您的代码的一些事情
Here are things I noticed about your code
- 您的数据库结构错误. (需要迁移以验证这一点)
- 从Authenticable扩展UserStatus
- 您保护了ID
- 您的关系定义不正确.
要确认,我们需要研究数据库的结构和迁移.
To confirm we would need to look into the database structure and migrations.
如果一个用户统计信息有很多用户,并且一个用户属于1个用户统计信息.
If a userstat have many users and a user belongs to 1 userstat.
迁移将
用户表将具有user_stat_id,而用户状态表将不会具有user_id
代码将如下所示.
UserStatus.php
UserStatus.php
class UserStats extends Model
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function users()
{
return $this->hasMany(User::class, 'user_stat_id');
}
}
User.php
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stat() {
return $this->belongsTo(UserStats::class, 'user_stat_id');
}
}
这篇关于Laravel:关系有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!