laravel 5.1 BelongsTo Reverse call

时间:2017-04-30 15:18:11

标签: php eloquent laravel-5.1

我所知道的:

$this->$parent->childs(); //we get childs data

我想知道的是:

$this->child->find($id)->parent(); //how to get childs parent without including model in controller | by just using eloquent

以下是员工和员工依赖模型的示例代码:

trait EmployeeRelationships{

    public function dependents(){
        return $this->hasMany(\App\DB\EmployeeDependent\EmployeeDependent::class);
    }

}

trait EmployeeDependentRelationships{

    /**
     * @return mixed
     */
    public function employee(){
        return $this->belongsTo(\App\DB\Employee\Employee::class, 'employee_id');
    }
}

1 个答案:

答案 0 :(得分:1)

如果要获得BelongsTo关系的反转,则需要在相应的模型上指定关系的倒数。例如:

员工类

class Employee extends Model
{
    public dependents()
    {
        return $this->hasMany(Dependant::class);
    }
}

依赖类

class Dependent extends Model
{
    public employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }
}

通过定义这些关系,您可以通过调用适当的方法来访问相关模型:

$dependents = Employee::first()->dependents; // Returns an eloquent collection
$employee   = Dependent::first()->employee;  // Returns a model of type Employee

请注意,在此示例中,使用first()方法来获取模型,您可以使用正确类型的任何对象执行此操作。