我的应用程序中有2个模型,'User'和'MedicineType'(每个用户属于一个MedicineType) .
我使用belongsTo()和hasMany()在两个模型之间 Build 了一对多关系 . hasMany()关系工作正常但belongsTo()不起作用 . 有谁知道我在哪里弄错了?
User :: find(1) - > medicine_type [this return nothing] MedicineType :: find(1) - > users [this returns 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
5 回答
您的关系不起作用的原因不是因为模型中指定的关系,而是因为用户模型中的方法命名而未指定外键 .
代替:
使用:
我希望这适合你;)
一切都在一起:
和:
测试是否有效:
这成功返回相关的medicine_type名称 .
我希望这可以帮助你进一步;)
也许Eloquent找到外键存在问题 . 试试这个:
编辑:
此外,Eloquent尝试查找表"medicinetypes"而不是"medecine_types",因此您还需要使用
$table
变量来指定它 .我犯了一个愚蠢的错误,就是不在关系方法中添加“return”!
确保你返回关系...显然这将 not 工作:
我将“medicine_type”更改为“medicineType”,并且每件事都可以......
在我的情况下,相关模型数据被删除,并且laravel在一般查询中不会获得软删除数据 . 要获得软删除的数据,您必须使用“withTrashed()或onlyTrashed()” .
您可以在此处查看文档 .
https://laravel.com/docs/5.6/scout#soft-deleting