Laravel 5.6: Many-to-many relationship returns empty object
我正在Laravel 5.6模型中建立多对多关系,但是由于我没有遵循Laravel的命名约定,因此我肯定在表/外键名称上犯了一个错误这使其无法正常工作。
与博客部分相关的表都带有
如前所述,我正在尝试在Laravel中建立关系:
型号:BlogPost.php
1 2 3 4 5 6 7 | /** * The tags that belong to the post. */ public function tags() { return $this->belongsToMany('App\\BlogTag', 'blog_posts_tags', 'post_id', 'tag_id'); } |
型号:BlogTag.php
1 2 3 4 5 6 7 | /** * The posts that belong to the tag. */ public function posts() { return $this->belongsToMany('App\\BlogPost', 'blog_posts_tags', 'tag_id', 'post_id'); } |
问题在于,当我调用
1 2 | $post = BlogPost::find($id); $tags = $post->tags(); |
我在哪里错了?
如果要获取相关的标签值,只需使用关系的名称
示例:
1 2 3 |