我是Laravel的新手,我正在开始构建Relationships。我很快就完成了一些比较简单的东西,但我正在努力做一些更高级的东西。
本质上,我有三件事:
- 联系人
- Moments
- 目标
在每个联系人下,我可以保存一个即时信息,我用所述联系人做过的不同事情。每个时刻也可以链接到一个目标。
现在,我正试图创建一个页面,显示我的所有目标,在该页面下显示我的每个时刻,对于每个时刻,我都想要一些关于时刻所附的基本信息。
以下是我的表格设置方式:
目标表:
- id - Goal name - Goal description
力矩表:
- id - userId - goalId - Moment name - Description
用户表
- id - firstname - lastname
所以我有:
class Goal extends Model
{
public function contact() {
return $this->belongsTo('App'Contact');
}
public function moments() {
return $this->hasMany('App'Moment', 'goalId');
}
}
我尝试了以下代码来获得所有结果:
$goals = Goal::with('moments', 'contact')
->where('authId', Auth::id())
->where('hidden', 'false')
->get();
dd($goals);
但所有联系人都返回为null。。。我尝试过不同的东西,但还没能弄清楚这个。
它使用hasManyThrough还是类似的东西?
编辑:所以我可以把它们放在一起,但不是按照我想要的顺序。使用:
public function contact() {
return $this->belongsTo('App'Contact', 'userId');
}
public function goal() {
return $this->belongsTo('App'Goal', 'goalId', 'id');
}
$moments = Moment::with('goal', 'contact')
->where('authId', Auth::id())
->where('hidden', 'false')
->get();
dd($moments);
我现在有一个$moments对象,它链接到正确的目标和联系人,但我想能够按目标排序,这可行吗?
谢谢你的帮助!
干杯,标记
已解决
使用以下方法解决:
public function contacts() {
return $this->hasMany('App'Contact', 'id', 'userId');
}
public function moments() {
return $this->hasMany('App'Moment', 'goalId');
}
$goals = Goal::with('moments', 'moments.contact')
->where('authId', Auth::id())
->where('hidden', 'false')
->get();
dd($goals);
已解决
使用以下方法解决:
public function contacts() {
return $this->hasMany('App'Contact', 'id', 'userId');
}
public function moments() {
return $this->hasMany('App'Moment', 'goalId');
}
$goals = Goal::with('moments', 'moments.contact')
->where('authId', Auth::id())
->where('hidden', 'false')
->get();
dd($goals);