Laravel hasManyThrough

2022-08-30 19:02:03

我正在努力弄清楚一个带有laravel的hayThlow概念。我有三张桌子:

Bookings
    -id (int)
    -some other fields

Meta
    -id (int)
    -booking_id (int)
    -metatype_id (int)
    -some other fields

MetaType
    -id (int)
    -name (string)
    -some other fields

我试图得到的是一个雄辩的模型,它允许我有一个带有多个MetaType类型的Meta记录的单个预订记录。我以为HaesManyThrough可能已经解决了这个问题,但现在我想也许这不是最好的方法。

在我的预订模型中,我有

public function bookingmeta() {
    return $this->hasMany('bookingmeta','booking_id');
}

public function bookingmetatype() {
    return $this->hasManyThrough('bookingmetatype','bookingmeta','booking_id','bookingmetatype_id');
}

但这无法生成正确的 SQL 并失败。我得到

select `new_bookingmetatype`.*, `new_bookingmeta`.`booking_id` 
from `new_bookingmetatype` 
inner join `new_bookingmeta` 
on `new_bookingmeta`.`bookingmetatype_id` = `new_bookingmetatype`.`id` 
where `new_bookingmeta`.`booking_id` in (57103)

而我真正想要实现的是

select `new_bookingmetatype`.*, `new_bookingmeta`.`booking_id` 
from `new_bookingmetatype` 
inner join `new_bookingmeta` 
on `new_bookingmeta`.`id` = `new_bookingmetatype`.`bookingmetatype_id`  
where `new_bookingmeta`.`booking_id` in (57103)

如果有人能为我指出正确的方向,我将不胜感激。谢谢。


答案 1

hasManyThrough根本不是路。它仅适用于如下关系:

A hasMany/hasOne B, B hasMany/hasOne C, then A hasManyThrough C (through B)

你在这里拥有的是一对多(),作为数据透视表。belongsToManymeta

所以你可以这样做(假设是表名,Booking和MetaType是模型):meta

// Booking model
public function meta()
{
  return $this->belongsToMany('MetaType', 'meta', 'booking_id', 'metatype_id')
        ->withPivot([ ARRAY OF FIELDS YOU NEED FROM meta TABLE ]);
}

然后,您可以访问所有关联的元类型:

$booking->meta; // collection of MetaType models

像这样查询它(预先加载):

$booking = Booking::with(['meta' => function ($q) {

  // query related table
  $q->where('someFieldOnMetaTypeTable', 'someValue')

    // and / or pivot table
    ->wherePivot('someFieldOnMetaTable', 'anotherValue');

}])->first();

或在相关表上设置约束以过滤预订:

$booking = Booking::whereHas('meta', function ($q) {

  // query related table
  $q->where('someFieldOnMetaTypeTable', 'someValue')

    // and / or pivot table
    ->where('meta.someFieldOnMetaTable', 'anotherValue');

})->first();

注意:仅当您急于加载关系时才有效,因此您无法在闭包中使用它。wherePivotwhereHas


答案 2

推荐