Laravel 4:模型关系不起作用(有点)


Laravel 4: Model Relationships Not Working (sort of)?

我的Laravel 4项目中有三个模型:EmployeeEmployeeClassEmployer:

class Employee extends Eloquent {
    protected $table = 'users';
    public function employee_class () {
        return $this->belongsTo('EmployeeClass', 'employee_class_id');
     }
}
class EmployeeClass extends Eloquent {
    protected $table = 'employee_classes';
    public function employees () {
        return $this->hasMany('Employee');
    }
    public function employer () {
        return $this->belongsTo('Employer');
    }
}
class Employer extends Eloquent {
    protected $table = 'employers';
    public function employee_classes () {
        return $this->hasMany('EmployeeClass');
    }   
}

EmployeeClass关系按预期工作。我可以执行EmployeeClass::find(1)->employees;EmployeeClass::find(1)->employer;,它会返回对象。

尝试对其他两个进行相同的调用(检索与EmployeeClass的关系)是不起作用的。这两行都返回空集:

Employee::find(1)->employee_class;
Employer::find(1)->employee_classes;

然而,奇怪的是,这两条线都能正常工作:

Employee::find(1)->employee_class()->first();
Employer::find(1)->employee_classes()->first();

第一个例子返回NULL(我认为它应该返回一个Collection)。第二个示例返回一个EmployeeClass对象(期望的实例)。

我想指出的是,每个表中都有一个id为1的条目,并且每个表都设置了FK=1,所以它们应该正确地连接。事实上,我认为EmployeeClass工作正常,并且获取查询并执行它(在第二组成功的代码中)也可以,这在一定程度上证明了这一点。

我确信我只是在做一些愚蠢的事情;也许换一双眼睛会有帮助!

我可以使用变通方法(第二组代码),因为它似乎可以工作,但如果可能的话,我希望它能干净、正确。。。

对于多词关系,函数应该在camelCase中(事实上,所有类方法都应该)。当访问模型的属性时,仍然允许以snake大小写访问关系名称(在您的示例中,为"employee_class",但请注意,这会绕过所有急切的加载,您应该以与关系方法名称完全相同的大小写访问关系。

在您的示例中,如果将employee_class(es)函数重命名为employeeClass(es),那么一切都应该正常。

// gets all employees and their class(es). the argument(s) for with()
// MUST match the names of the methods exactly.
Employee:with('employeeClass')->get();
// you MUST access eager loaded data in the same case as in with().
// if you access via snake case, eager loading is bypassed.
$employee->employeeClass;
// this also works but should generally be avoided.
Employee::find(1)->employeeClass()->first();