我有三个类似下面的表格。
posts
_id - integer
name - string
sentences
_id - integer
post_id - integer
name - string
translations (word by word)
_id - integer
post_id - integer
sentence_id - integer
word_id - integer
name - string在PostController.php中,我尝试获取数据,如下所示
return Post::with(['sentences', 'sentences.translations'])->limit(2)->get();我在post.php模型中有函数,如下所示
protected $primaryKey = '_id';
public function sentences()
{
return $this->hasMany('App\Model\sentence', 'post_id','_id');
}我在sentences.php模型中有函数,如下所示
protected $primaryKey = '_id';
public function translations()
{
return $this->hasMany('App\Model\translation', 'sentence_id','_id');
}我想获取帖子连同句子和翻译。
我可以获取帖子和句子,但我在尝试获取翻译时遇到了问题。
我正在获取sentence_id与sentences表的id匹配的所有translations,但post_id与当前post id of post表不匹配。
发布于 2018-07-14 13:16:50
如果您已将主键命名为id以外的任何名称,则需要在每个模型上设置主键名称:
class Post extends Model {
protected $primaryKey = '_id';
}将您的关系与正确的名称进行匹配:
return $this->hasMany(Sentence::class, 'post_id','_id');https://stackoverflow.com/questions/51325904
复制相似问题