【问题标题】:Laravel Eloquent Relationship with Pivot Table and ConditionalsLaravel Eloquent 与数据透视表和条件的关系
【发布时间】:2018-06-09 04:52:09
【问题描述】:

希望在 Eloquent 模型中实现数据透视表关系,但我不确定是否可行。

为了说明,假设我们有一个系统可以跟踪哪些电影在哪些影院播放。还假设影院可以通过促销折扣来降低票价。某些折扣可能有限制(最低票价或仅限 G 级电影等),折扣可能可以组合,也可能不能组合。

数据库结构:

movies (id, title...)
theaters (id, name,...)
discounts (id, theater_id, discount_amount, min_price, can_combine)
theater_movies (id, movie_id, theater_id, ticket_price)
movie_discounts (id, movie_id, discount_id)

Laravel Theater 电影模型

class TheaterMovie extends Model
{
   public function discounts()
      return $this->hasManyThrough(
            Discount::class,
            MovieDiscount::class,
            'movie_id', // Foreign key on movie_discounts table...
            'id', // Foreign key on discounts table...
            'movie_id', // Local key on theater_movies table...
            'discount_id' // Local key on movie_discounts table...
        ) 
}

但这并没有捕捉到theater_movies.theater_id = discounts.theater_id 的关系,理想情况下还会检查ticket_price 和min_price。

【问题讨论】:

  • hasManyThrough 关系实际上并不使用枢轴,而是 belongsToMany 使用。将hasManyThrough 视为A 有很多BB 有很多C 所以A 有很多C 尽管B
  • return $this->belongsToMany(Discount::class, 'movie_discount','movie_id','discount_id','movie_id');但是我在哪里可以使用 theatre_movies.theater_id = discounts.theater_id?某种范围会起作用吗?
  • TheatreMovie 类对于列出所有影院的同一部电影,价格调整为任何当前折扣至关重要。

标签: laravel eloquent


【解决方案1】:

我认为在 Theatre 和 Movie 模型上使用简单的关系可能比尝试引入 TheaterMovie 类更容易。

例如,在 Theatre 课上,您与电影的关系如下:

public function movies()
{
    return $this->belongsToMany("App\Movie")->orderBy('name');
}

然后要获得您的枢轴,您可以做类似的关系,但在剧院模型上添加枢轴:

public function discounts()
{
    return $this->belongsToMany("App\Discount")->withPivot('discount_amount', 'min_price', 'can_combine')->orderBy('name');
}

从这里,当您从剧院模型调用关系时,您可以像这样使用枢轴:

$theater->pivot->discount_amount;

等等。如果愿意,您可以在电影表上放置类似(甚至相同)的折扣关系,以便从其他相关模型中获取信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2018-09-19
    • 2023-02-05
    • 2017-07-22
    • 2014-08-26
    • 2019-01-25
    相关资源
    最近更新 更多