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

I'm having difficulty defining the relationship that:

A user owns many listings. Each listing has many quotes and each quote may belong to many listings. Structure:

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

My issue is im getting confused about the quotes_users setup above.

The user will want to see each quote they have along with the connected listing. They may then update their version of the quote, accepting or rejecting it. Before using Laravel, I would not have put user_id inside quotes_users, instead naming it quotes_listings, main reason it sits in this table is my lack of knowledge of laravel relationships.

Models:

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');
    }
}

With this current setup, struggling to show each listing when using User::quotes() as quotes_users does not have a model and hence I can not tell laravel listing_id should be connected to a listing.

Any help would be much appreciated!

Your user relation is incorrect, should be return $this->hasMany instead of return $this->belongsToMany.

Still, your table doesn't look right to me. I think it should be called listings_quotes, since the many-to-many relation is between those two, not users and quotes.

An easy setup would be:

  • User hasMany listing
  • Listing belongsToOne User.
  • Listing belongsToMany quote.
  • Quote belongsToMany Listing.

That way, you could access Quotes from user indirectly like this: User->Listing->Quote

Or, you could use the hasManyThrough relation

You can check this other answer, I think it has a similar problem