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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序