【发布时间】:2020-04-27 14:56:45
【问题描述】:
我有一个基金表,其中包含与不同院系、研究所、倡议等相关联的资金。一个基金属于许多院系,而院系可以有很多基金。
我还在用户和学院表之间建立了多对多关系,以确保用户只能看到与特定学院相关联的资金。
funds table
--------------------
id
name
...
faculties table
--------------------
id
name
...
faculties_funds table
---------------------
id
faculty_id
fund_id
users table
---------------------
id
fname
...
faculties_user
--------------------
id
faculty_user
user_id
我是这样定义我的关系的:
class Fund extends Model
{
public function faculties(){
return $this -> belongsToMany('App\Faculty');
}
}
class Faculty extends Model
{
public function funds(){
return $this -> belongsToMany('App\Fund');
}
public function users(){
return $this -> belongsToMany('App\User');
}
}
class User extends Model{
public function faculties(){
return $this -> belongsToMany('App\Faculty');
}
}
我需要的是能够获取与授权用户映射到的学院相关的所有资金。我单独测试了这些关系,它们都有效,我可以 dd 响应也有一个包含枢轴信息的关系数组,但我无法获得我想要的资金。
在编写查询以获得结果方面最好不使用原始查询或如果我需要重做我的数据库结构,我们将不胜感激。
到目前为止,这是我的代码:
public function index()
{
$user = Auth::user();
if(Auth::user() -> role == 'superadmin'){
return view('funds.index')
-> with('funds', Fund::all());
}else{
dd( Auth::user() -> faculties); //I can see the faculties associated and also
dd( Auth::user() -> faculties() -> funds ); //doesnt work
}
}
【问题讨论】:
-
我很惊讶你们的关系正在发挥作用,因为标准表命名约定不受尊重
-
@ADELNAMANI - 感谢您向我指出这一点,以前从未使用过它。我的关系不是使用枢轴定义的,但对于未来,我将对其进行研究并以更简化的方式实施。