我有点卡在这... 我有3个表:摄影师,语言和languages_spoken(中间表)。
我正在尝试检索摄影师所说的所有语言。我定义了这样的模型:
class Photographer extends Eloquent {
/**
* Defining the many to many relationship with language spoken
*
*/
public function languages() {
return $this->belongsToMany('Language', 'languages_spoken', 'language_id', 'photographer_id');
}
class Language extends Eloquent {
/**
* Defining the many to many relationship with language spoken
*
*/
public function photographers() {
return $this->belongsToMany('Photographer', 'languages_spoken', 'language_id', 'photographer_id')
->withPivot('speakslanguages');
}
这就是我试图检索登录摄影师的所有结果的方法:
$photographer = Photographer::where('user_id', '=', $user->id);
if ($photographer->count()) {
$photographer = $photographer->first();
// TEST
$spokenlang = $photographer->languages;
die($spokenlang);
// END TEST
} else {
return App::abort(404);
}
问题是在我的数据库中我有4个同一摄影师的条目。但是当我这样做时,我只得到最后的结果......
[{" ID":" 3"" LANGUAGE_NAME":"南非荷兰语""的updated_at&# 34;:" -0001-11-30 00:00:00"," created_at":" -0001-11-30 00:00:00", " native_name":"南非荷兰语"" ISO639_1":" AF""枢轴" {" LANGUAGE_ID":" 3"" photographer_id":" 3"}}]
对于什么是错误的任何想法?
非常感谢你的帮助!!!
答案 0 :(得分:1)
belongsToMany的第三个参数应该是 foreign 键。
在摄影师课上:
public function languages() {
return $this->belongsToMany('Language', 'languages_spoken', 'language_id', 'photographer_id');
}
......应该是:
public function languages() {
return $this->belongsToMany('Language', 'languages_spoken', 'photographer_id');
}
在语言课程中:
public function photographers() {
return $this->belongsToMany('Photographer', 'languages_spoken', 'language_id', 'photographer_id')
->withPivot('speakslanguages');
}
应该是:
public function photographers() {
return $this->belongsToMany('Photographer', 'languages_spoken', 'language_id')
->withPivot('column1', 'column2', 'column3'); // withPivot() takes a list of columns from the pivot table, in this case languages_spoken
}
但是,由于你甚至没有使用奇怪的键,你根本不需要传递第三个参数。
所以这很好:
public function languages() {
return $this->belongsToMany('Language', 'languages_spoken');
}
和
public function photographers() {
return $this->belongsToMany('Photographer', 'languages_spoken')
->withPivot('column1', 'column2', 'column3'); // withPivot() takes a list of columns from the pivot table, in this case languages_spoken
}