我的应用程序中有2个模型,'User'和'MedicineType'(每个用户属于一个MedicineType)。
我使用belongsTo()和hasMany()在两个模型之间建立了一对多关系。 hasMany()关系可以正常工作,但是belongTo()不起作用。有人知道我在哪里弄错了吗?
User :: find(1)-> medicine_type [这什么也没返回]
MedicineType :: find(1)-> 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
您的关系不起作用的原因不是由于模型中指定的关系,而是由于用户模型中的方法命名且未指定外键。
而不是:
public function medicine_type()
{
return $this->belongsTo('MedicineType');
}
用途:
public function medicineType()
{
return $this->belongsTo('MedicineType', 'id');
}
我希望这对您有用;)
所有内容:
<?php // app/models/MedicineType.php
class MedicineType extends Eloquent {
// Determines which database table to use
protected $table = 'medicine_types';
public function users()
{
return $this->hasMany('User');
}
}
和:
<?php // app/models/User.php
class User extends Eloquent {
// Determines which database table to use
protected $table = 'users';
public function medicineType()
{
return $this->belongsTo('MedicineType', 'id');
}
}
测试是否有效:
$user = User::find(1);
return $user->medicineType->name;
这将成功返回相关的医学类型名称。
我希望这可以帮助您进一步;)
也许Eloquent找到外键存在问题。试试这个:
class User extends Eloquent {
public function medicine_type()
{
return $this->belongsTo('MedicineType', 'medicine_type_id');
}
}
编辑:
此外,Eloquent尝试查找表“ medicinetypes”而不是“ medecine_types”,因此您还需要使用$table
变量进行指定。
class MedicineType extends Eloquent {
protected $table = 'medicine_types';
public function users()
{
return $this->hasMany('User');
}
}
我犯了一个愚蠢的错误,没有在关系方法中添加“ return”!
确保您返回该关系...显然,这将not起作用:
public function medicineType()
{
$this->belongsTo('MedicineType', 'id');
}
我将“ medicine_type”更改为“ medicineType”,一切正常...
在我的情况下,相关模型数据已删除,而laravel在一般查询中不会获得软删除的数据。要获取软删除的数据,您必须使用“ withTrashed()或onlyTrashed()”。
您可以在这里查看文档。
在大多数情况下,票数第一的答案可能是最好的答案。但是,如果您仍然在加载相关关系时遇到麻烦,也没有运气。.
还有另一件事可能起作用。查看每个模型的表及其索引或外键。就我而言,我已更改了表名,但从未更新所涉及的索引和外键。
解决方案。
A:(Feeling Lazy)只需删除关联的索引或外键。
B :(我不是懒惰)通过laravel迁移删除表,并使用适当的外键重新运行artisan迁移。
型号:
class User extends Eloquent {
public function medicine_type()
{
return $this->belongsTo('MedicineType');
}
}
UserController.php
$users= App\User::all();
foreach ($users as $user) {
echo $user->medicine_type->name;
}