Laravel的belongsTo关联方法不起作用。

12 浏览
0 Comments

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

0
0 Comments

Laravel belongsTo方法不起作用的原因是在关联方法中没有添加"return"关键字。需要确保在关联方法中添加返回关联的代码。以下代码将无法正常工作:

public function medicineType() 
{
    $this->belongsTo('MedicineType', 'id');
}

需要添加返回关联的关键字:

public function medicineType() 
{
    return $this->belongsTo('MedicineType', 'id');
}

也许不要展示不起作用的代码,而是展示起作用的代码,这样会更清晰明了。

0
0 Comments

问题: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;来检查数据库中的数据。

如果以上方法没有解决问题,可以进一步查看代码实现以及数据库中的数据,以确定是否还有其他问题。

0
0 Comments

问题出现的原因是User模型中方法的命名方式以及没有指定外键。解决方法是将User模型中的方法名改为驼峰命名法,并指定外键。

具体代码如下:

hasMany('User');
   }
}

belongsTo('MedicineType', 'id');
   }
}

测试是否生效:

$user = User::find(1);
return $user->medicineType->name;

这将成功返回相关的medicine_type的名称。

希望这对你有帮助。

0