Laravel属于不工作

Yas*_*ari 23 php orm laravel eloquent laravel-4

我的应用程序中有2个模型,'User'和'MedicineType'(每个用户属于一个MedicineType).

我使用belongsTo()和hasMany()在两个模型之间建立了一对多关系.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');
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的数据库结构:

users:
    id
    name
    medicine_type_id 

medicine_types:
    id
    name
Run Code Online (Sandbox Code Playgroud)

Mel*_*ans 43

您的关系不起作用的原因不是因为模型中指定的关系,而是因为用户模型中的方法命名而未指定外键.

代替:

public function medicine_type()
{
    return $this->belongsTo('MedicineType');
}
Run Code Online (Sandbox Code Playgroud)

使用:

public function medicineType()
{
    return $this->belongsTo('MedicineType', 'id');
}
Run Code Online (Sandbox Code Playgroud)

我希望这适合你;)

一切都在一起:

<?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');
   }

}
Run Code Online (Sandbox Code Playgroud)

和:

<?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');
   }

}
Run Code Online (Sandbox Code Playgroud)

测试是否有效:

$user = User::find(1);
return $user->medicineType->name;
Run Code Online (Sandbox Code Playgroud)

这成功返回相关的medicine_type名称.

我希望这可以帮助你进一步;)

  • 我同意@briankip - 外键不应该是`medicine_type_id`而不是`id`吗?当id匹配时,它与`id`一起使用可能只是一些记录的巧合,但生成的查询可能完全错误地加入`medicine_types.id = users.id`而不是`users.medicine_type_id = medicine_types. id`,应该如此.我总是查看DebugBar来验证生成的查询是否正确. (8认同)
  • 非常感谢.我没有说过这种方法必须是驼峰式的 - 没有下划线允许!我在文档中想念这个吗? (2认同)

Jos*_*eph 10

也许Eloquent找到外键存在问题.试试这个:

class User extends Eloquent {

    public function medicine_type()
    {
        return $this->belongsTo('MedicineType', 'medicine_type_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

此外,Eloquent试图找到表"medicinetypes"而不是"medecine_types",所以你需要指定使用$table变量.

class MedicineType extends Eloquent {
    protected $table = 'medicine_types';

    public function users()
    {
        return $this->hasMany('User');
    }
}
Run Code Online (Sandbox Code Playgroud)