【问题标题】:Laravel - 2xHasMany Relations one other TableLaravel - 2xHasMany 关系另一个表
【发布时间】:2018-01-08 03:01:20
【问题描述】:

我有桌子Messages

包含fromto

对应于表Users中的一些用户。

所以我需要类似(用户模型中的 hasMany 关系 - hasMany 消息)

public function Messages()
    {
        return $this->hasMany('App\Models\Messages', 'from', 'id');
        return $this->hasMany('App\Models\Messages', 'to', 'id');
    }

但是有两个返回,第二个是 Unreachable 语句。 那么在多于一个的情况下如何管理多个关系呢?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    首先你不能像这样使用 2 return

    public function Messages()
    {
        return $this->hasMany('App\Models\Messages', 'from', 'id');
        return $this->hasMany('App\Models\Messages', 'to', 'id');
    }
    

    如果你把它分成2个这样的方法会更好:

    public function to()
    {
        return $this->hasMany('App\Models\Messages', 'to', 'id');
    }
    
    public function from()
    {
        return $this->hasMany('App\Models\Messages', 'from', 'id');
    }
    

    【讨论】:

      【解决方案2】:

      创建第二个关系:

      public function messageRetrieved()
      {
          return $this->hasMany('App\Models\Messages', 'from', 'id');
      }
      
      public function messageSend()
      {
          return $this->hasMany('App\Models\Messages', 'to', 'id');
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-30
        • 1970-01-01
        • 2021-01-07
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        相关资源
        最近更新 更多