douwu7563 2014-01-09 13:51
浏览 84
已采纳

如何使用Laravel中的Eloquent为同一两个表创建不同的多对多关系

I have 2 tables 'User' and 'Content'. A user can favourite content, so I use a pivot table User_Content to establish the many to many relationship between the user and the content they have favourited. This is fine.

A user can also purchase content. This would be the same relationship as above (User_Content) but would be completely different data.

How do I setup a relationship like this where the relationship between tables is the same but the content is different - can this be done successfully in Laravel using Eloquent? Or is there a completely different way I should be approaching this?

  • 写回答

1条回答 默认 最新

  • dqjcb132285 2014-01-09 15:41
    关注

    Just set up a user_purchase and user_favorite table both containing user_id and content_id fields

    then set up the model

    as

    class User extends Eloquent{
        public function purchases()
        {
            return $this->belongsToMany('Content','user_purchase');
        }
    
        public function favorites()
        {
            return $this->belongsToMany('Content','user_favorite');
        }
    }
    
    class Content extends Eloquent{
    
        public function buyers()
        {
            return $this->belongsToMany('User','user_purchase');
        }
    
        public function favorites()
        {
            return $this->belongsToMany('User','user_favorite');
        }
    }
    

    The second column indicates which table to check for the many to many relationship

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

报告相同问题?

悬赏问题

  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata