Laravel 4 Laravel 4:使用错误行执行查询的关系
我有一个关系,我正试图得到工作,似乎是由错误的列搜索。我有一个模型,userwords,它应该得到一个相关的单词。我希望它使用userword表中的word_id列,通过word表中的id来搜索单词,但它似乎使用userword行的id来搜索单词。我想,如果我告诉它在hasOne()的第三个参数中使用哪一列,它可能会工作,但没有用。有关守则是:Laravel 4 Laravel 4:使用错误行执行查询的关系,laravel-4,eloquent,Laravel 4,Eloquent,我有一个关系,我正试图得到工作,似乎是由错误的列搜索。我有一个模型,userwords,它应该得到一个相关的单词。我希望它使用userword表中的word_id列,通过word表中的id来搜索单词,但它似乎使用userword行的id来搜索单词。我想,如果我告诉它在hasOne()的第三个参数中使用哪一列,它可能会工作,但没有用。有关守则是: public function word(){ return $this->hasOne('Word', 'id', 'word_id')
public function word(){
return $this->hasOne('Word', 'id', 'word_id');
}
任何帮助或想法都将不胜感激!如果你需要更多信息,请告诉我,我会在这里更新!非常感谢 您的父表是
userword
,相关的子表是word
,在这种情况下,userword
模型应该包含以下方法来建立与word
表的关系:
class Userwords {
protected $table = 'userword';
public function word(){
return $this->hasOne('Word', 'userword_id'); // use the foreign key here
}
}
在这种情况下,您的word
表应该包含userword\u id
作为外键。因此,如果您有一个不同的外键定义的单词表,那么使用该外键代替userword\u id
还请记住,表格应使用单词的复数名称,例如,words
应为表格名称,但您使用的是word
,模型应使用单数名称,例如,words
表格应使用word
,因此,您在这里有不同的名称约定,因此在word
模型中使用protected$table='word'
,在Userwords
模型中使用protected$table='userword'
。最后,应该是这样的:
class Userword {
// change the table name in database (use userwords)
protected $table = 'userwords';
public function word(){
return $this->hasOne('Word', 'userword_id'); // use the foreign key here
}
}
对于单词
表格,应为:
class Word {
// change the table name in database (use words)
protected $table = 'words';
public function userwords(){
return $this->belongsTo('Userword');
}
}
请阅读手册以了解有关的更多信息