【发布时间】: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有很多B和B有很多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 类对于列出所有影院的同一部电影,价格调整为任何当前折扣至关重要。