Laravel的belongsTo关联方法不起作用。
Laravel的belongsTo关联方法不起作用。
我在我的应用程序中有两个模型,'User'和'MedicineType'(每个User属于一个MedicineType)。
我使用belongsTo()和hasMany()在两个模型之间建立了一对多的关系。hasMany()关系运行正常,但belongsTo()关系不起作用。有人知道我犯了什么错误吗?
User::find(1)->medicine_type [这返回空]
MedicineType::find(1)->users [这返回users]
以下是模型的代码:
class MedicineType extends Eloquent { public function users() { return $this->hasMany('User'); } } class User extends Eloquent { public function medicine_type() { return $this->belongsTo('MedicineType'); } }
这是我的数据库结构:
users: id name medicine_type_id medicine_types: id name
问题:Laravel的belongsTo关联关系不起作用
原因:可能是由于Eloquent无法找到外键引起的。另外,Eloquent在查找表名时会尝试寻找"medicinetypes"而不是"medicine_types",因此需要使用$table变量来指定表名。
解决方法:
1. 在User类中,确保正确指定了外键:
class User extends Eloquent { public function medicine_type(){ return $this->belongsTo('MedicineType', 'medicine_type_id'); } }
2. 在MedicineType类中,使用$table变量来指定表名:
class MedicineType extends Eloquent { protected $table = 'medicine_types'; public function users(){ return $this->hasMany('User'); } }
3. 确保数据库中有与关联关系匹配的数据,可以使用MedicineType::find(1)->users;
来检查数据库中的数据。
如果以上方法没有解决问题,可以进一步查看代码实现以及数据库中的数据,以确定是否还有其他问题。