drdawt9210 2017-04-30 15:18
浏览 40

laravel 5.1 BelongsTo Reverse call

What i know:

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

what i want to know how:

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

heres my sample code of employee and employeeDependent model:

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条回答 默认 最新

  • douchui4815 2017-04-30 16:04
    关注

    If you want to get the reverse of a BelongsTo relationship you need to specify the inverse of the relationship on the corresponding model. For example:

    Employee Class

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

    Dependent Class

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

    With these relationships defined you can then access the relevant models by calling the appropriate methods like so:

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

    Note that in this example using the first() method to grab a model, you can can do this with any object of the correct type.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入