dongyan7950 2014-07-09 11:37
浏览 35

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!

  • 写回答

1条回答 默认 最新

  • douan2907 2014-07-09 12:10
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来