dongxibeng5324 2014-07-09 12:48
浏览 79

Laravel多重关系

I am trying to get my head around some relationships between models in Laravel.

I would like to define the relationship between the following models:
User - the users
Campaign - a campaign
Call - a phone call
Lead - Lead/client
Sale - A sale
Appointment - A scheduled phone call.

This is the way the relationship should be:

A user can be assigned to many campaigns.
A user can have many calls.
One user can have many appointments.
One call belongs to one user.
One call belongs to one campaign.
A campaign can have many calls.
A campaign can have many sales
A lead can be assigned to many campaigns.
A lead can have many sales
One lead belongs to one user in one campaign.
One lead can have many calls
One sale belongs to one campaign
One sale belongs to one user
One appointments belongs to one lead.

I uncertain about how to setup the relationship. Its easy with the one-to-one or many-to-one.
But what about this:
Call->User (one-to-one)
Call->Campaign (one-to-one)
Campaign->Call (one-to-many)
User->Call (one-to-many)


Hopefully I managed to explain it clear enough. Thanks.

  • 写回答

1条回答 默认 最新

  • doucheng1063 2014-07-09 13:28
    关注

    I'd recommend reading the Laravel docs on relationships again.

    Taking the Call/User relationship as an example, here's what you're looking at:

    User  --------> Call
    (one)           (many)
    

    This is clearly a one to many relationship. And if you want to set up both sides of this relationship in terms of an Eloquent model, the relationships are this:

    A User hasMany Calls
    
    A Call belongsTo a User
    

    These terms are taken directly from the documentation, in the section entitled One To Many.

    So, in code...

    User Model

    public function Calls()
    {
        $this->hasMany("Call");
    }
    

    (notice that I've made the method name plural - this is my own preference, since using $user->Calls will return a collection if items).

    Call Model

    public function User()
    {
        $this->belongsTo("User");
    }
    

    Rather than taking the two sides of a relationship in isolation, as you seem to have done in your analysis, consider both sides of the relationship at the same time.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度