首页 > 解决方案 > Relationships with Laravel

问题描述

I do not know why, but the result that I am getting it's empty... I am trying to make a relation between a supervisor and a branc_office.

The branch_office just has one supervisor. The supervisors can have many branch_office to manage.

So the relation it's 1 to Many.

My tables are:

The id_supervisor and id_user make the relation between them.

id_supervisor(foreign key) ----- id_user(primary key)

My models:

User.php

use Notifiable;

protected $primaryKey = 'id_user';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'full_name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

 /**
 * Get the comments for the blog post.
 */
public function branch_offices()
{
    return $this->hasMany('App\Branch_Office', 'id_supervisor');
}

Branch_office.php

protected $table = 'branch_offices';

protected $primaryKey = 'id_branch_office';

/**
 * Get the post that owns the comment.
 */
public function supervisor()
{
    return $this->belongsTo('App\User', 'id_user');
}

In the controller I am doing this:

$branch_office_detail = Branch_Office::find(1)->supervisor()->first();

but it displays a null or empty result... and there is a branch_office with id = 1

So I wonder, what it's wrong? becaiuse I have done this step by step and It's not working.

Thanks.

标签: phplaravellaravel-5eloquent

解决方案


protected $table = 'branch_offices';

protected $primaryKey = 'id_branch_office';

public function supervisor()
{
    return $this->belongsTo('App\User', 'id_supervisor', 'id_user');
}

在几乎所有的关系中,第一个参数是模型,第二个是外键,第三个是本地键。还有belongsTo函数只返回一条记录或null,你不需要使用first()

BranchOffice::find(1)返回分支;

BranchOffice::find(1)->supervisor返回分支 1 的主管

BranchOffice::with('supervisor')->find(1)与主管一起返回办公室


推荐阅读