php - 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:
Branch_office
fields:id_branch_office
id_supervisor
branch_office
User
fields:id_user
name
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.
解决方案
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)
与主管一起返回办公室
推荐阅读
- python - 在 Python 中自定义集合交集
- arrays - 你如何比较两个在Powershell中都有多个属性和对象的数组
- android - 从 Flutter android MainActivity 启动新的外部 Activity
- php - Str_replace 用 php 中的数据库插入标题
- javascript - Electron / Nativefier Web App - 新窗口打印问题 [HTML, JS]
- asynchronous - Dart 等待异步函数完成而不等待
- sql - 当我只期望一个值时,DB2 SQL 函数返回多个值
- java - 从 mapbox 复制了一个缺少变量的教程,它不会运行
- firebase - .valueChanges() 和 .get() 有什么区别
- python-3.x - 试图使 Gnome 排序递归