我正在使用Laravel,我在使用雄辩表达创建一个拥有教练ID的团队时遇到了问题。我有用户(可以成为教练的基本用户),然后我有教练,他们只有一个团队,最后是团队,可以有1或2个教练。他们的表格:
Users:
id | email | password | coach_id (null is default)
Coaches:
id | user_id | ... (other unnecessary coach info)
Teams:
id | coach_id | ... (other unnecessary team info)
我尝试在TeamController的方法中创建团队(在Youtube https://youtu.be/z-1bdYTNWm8?t=6m50s上的laravel教程之后):
$team = new Team();
$team->team_name = $team_name;
$team->organization = $organization;
$team->address = $address;
$request->user()->coach()->team()->save($team);
我的用户模型:
public function coach(){
return $this->hasOne('App\Coach');
}
我的教练模特:
public function user(){
return $this->belongsTo('App\User');
}
public function team(){
return $this->hasOne('App\Team');
}
我的团队模特:
public function coach(){
return $this->belongsToMany('App\Coach');
}
但是我收到了这个错误:
BadMethodCallException in Builder.php line 2450:
Call to undefined method Illuminate\Database\Query\Builder::team()
答案 0 :(得分:1)
您可以尝试:
$team = new Team();
$team->team_name = $team_name;
$team->organization = $organization;
$team->address = $address;
$request->user()->coach->team()->save($team);
注意 - 从()
关系中删除coach
。
<强>更新强>
当您添加括号()
时,它会创建查询构建器,并且您在team
模型中没有任何名为User
的关系,因此Laravel会抛出错误。
但是当你执行$request->user()->coach
时,它会返回Coach
模型的对象,然后您可以通过关系名称team
进行查询。