Php 与拉威尔的关系
我不知道为什么,但我得到的结果是空的。。。我试图在Php 与拉威尔的关系,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我不知道为什么,但我得到的结果是空的。。。我试图在主管和分支机构之间建立关系 分公司只有一名主管。 主管可以管理多个分支机构 所以它是一对多的关系 我的桌子是: 分支机构字段: id\u分行办公室 id\u主管 分支机构 用户字段: id\u用户 name id\u主管和id\u用户建立了它们之间的关系 id\u主管(外键)---id\u用户(主键) 我的模型: User.php use Notifiable; protected $primaryKey = 'id_user';
主管
和分支机构
之间建立关系
分公司
只有一名主管
。
主管
可以管理多个分支机构
所以它是一对多的关系
我的桌子是:
字段:分支机构
id\u分行办公室
id\u主管
分支机构
字段:用户
id\u用户
name
id\u主管
和id\u用户
建立了它们之间的关系
id\u主管
(外键)---id\u用户
(主键)
我的模型:
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');
}
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');
}
Branch\u office.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');
}
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');
}
在控制器中,我正在执行以下操作:
$branch_office_detail = Branch_Office::find(1)->supervisor()->first();
但它会显示一个null或空结果。。。还有一个id为1的分支机构
所以我想知道,怎么了?因为我已经一步一步地做了,但它不起作用
谢谢
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')->查找(1)
与主管一起返回办公室