Laravel 4型号:对于一个数据透视表盒感到困惑

时间:2014-07-09 11:37:08

标签: php mysql laravel model

我很难定义以下关系:

用户拥有许多商家信息。每个列表都有很多引号,每个引用可能属于许多列表。结构:

users
id - integer

listings
id - integer
user_id - integer

quotes
id - integer
title - string

quotes_users (pivot (issue here))
id - integer
quote_id - integer
listing_id - integer
user_id - integer
accepted_at - datetime
rejected_at - datetime

我的问题是我对上面的quotes_users设置感到困惑。

用户希望查看他们拥有的每个报价以及连接的列表。然后他们可以更新他们的报价版本,接受或拒绝它。在使用Laravel之前,我不会将user_id放在quotes_users中,而是将其命名为quotes_listings,它在此表中的主要原因是我对laravel关系缺乏了解。

型号:

class User extends Eloquent {

    public function quotes()
    {
        return $this->belongsToMany('Quote', 'quotes_users')->withTimestamps('accepted_at', 'rejected_at')->withPivot('accepted_at', 'rejected_at')->orderBy('created_at', 'DESC');
    }
}

class Quote extends Eloquent  {

    public function users()
    {
        return $this->belongsToMany('User', 'quotes_users')->withTimestamps('accepted_at', 'rejected_at')->withPivot('accepted_at', 'rejected_at')->orderBy('created_at', 'DESC');
    }
}

使用当前设置,在使用User :: quotes()作为quotes_users时,努力显示每个列表没有模型,因此我无法告诉laravel listing_id应该连接到列表。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您的用户关系不正确,应该是return $this->hasMany而不是return $this->belongsToMany

不过,你的桌子对我来说不合适。我认为它应该被称为listing_quotes,因为多对多关系是在这两者之间,而不是用户和引号。

简单的设置是:

  • 用户有许多商家信息
  • 列出belongsToOne用户。
  • 列出belongsToMany引用。
  • 引用belongsToMany列表。

这样,您可以间接访问用户的引号,如下所示: 用户> Listing->报价

或者,您可以使用hasManyThrough relation

您可以查看this other answer,我认为它有类似的问题