doo58088 2015-01-20 21:30
浏览 27
已采纳

Laravel在模型上使用链接表

So I have the tables tags, posts and a link table for these Now I want to get all the tags from the current post.

Now I want to get all the tags related to this post.

I made a model "Tag" (with no functions yet, just extending Eloquent)

How can I use this model to get all the tag names/titles based on the current post id, or do I need a seperate model for the Linking table(Which seems incorrect to me)?

I'm kinda lost in it right now, probably due to too much searching. Anyone can help me out here?

SOLVED

$post = Post::where('id', $id)->first(); 
$tags= $post->tags;

Tags function in the Post model:

public function tags()
{
    return $this->belongsToMany('Tag');
}
  • 写回答

1条回答 默认 最新

  • dtds8802 2015-01-20 21:47
    关注

    Add the following function to your Post model

    public function tags()
    {
        return $this->belongsToMany('Tag');
    }
    

    Now you can call $post->tags()->getResults() to get all tags of a post.

    Corresponding docs: http://laravel.com/docs/4.2/eloquent#many-to-many

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备