【问题标题】:The relationship of one model一个模型的关系
【发布时间】:2020-11-24 17:27:27
【问题描述】:

我对 Laravel 关系有疑问。

我需要根据这张表建立关系:

issuerfriend 需要联合起来。关系将返回用户 ID 在issuerfriend 中的所有行。目前代码如下所示:

return DB::table('contacts')->select()->where('friend', $this->id)->orWhere('issuer', $this->id)->where('status', 'approved');

以前我用过那个方法,但是没有关系,因为attach()是未定义的。

    private function contactsIssued() {
        return $this->belongsToMany(User::class, 'contacts','issuer', 'friend');
    }

    private function contactsFriended() {
        return $this->belongsToMany(User::class, 'contacts','friend', 'issuer');
    }

    public function contacts() {
        return $this->contactsIssued()->union($this->contactsFriended()->toBase());
    }

所以,我需要建立一个包含两个外部列的关系。

对不起,我的英语可能会被破坏,因为它不是我的母语。

【问题讨论】:

  • 那么您遇到的具体问题是什么?你想达到什么目标,你在哪里失败了?
  • 所以,我需要一个两个相等列的关系,但我不知道该怎么做
  • @wschopohl 添加了主要问题,抱歉
  • 你不见了get(), return DB::table('contacts')->select()->where('friend', $this->id)->orWhere('issuer', $this->id)->where('status', 'approved')->get();
  • @STA 主要问题与此无关

标签: php mysql laravel


【解决方案1】:

这看起来像one to many 关系,但您使用的是belongsToMany,它是many to many 关系并且需要pivot 表。

如果您的 user 模型具有许多 contact 模型,那么在您的 contact 模型中,您应该通过使用 belongsTo 来使用 one to many 关系。

但是如果你有 3 个表格,你没有在你的问题中说,那么请编辑你的问题并提供你的模型和它们之间的关系。

【讨论】:

  • Emm.. 请看一下表格,它显然看起来像数据透视表
  • 我说如果是多对多,请提供您的数据库结构,以便我提供帮助。但你只是投了反对票.. 很抱歉帮助你
  • 我不会否决你的回答,因为我没有声望否决。
  • 在 StackOverflow 中,没有任何方法可以找到对您的问题投反对票的人
猜你喜欢
  • 1970-01-01
  • 2018-04-15
  • 2017-01-20
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多