Gre*_*reg 14 php laravel eloquent
我正在努力通过laravel了解hasManyThrough概念.我有三张桌子:
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
Run Code Online (Sandbox Code Playgroud)
我想要得到的是一个Eloquent模型,它允许我拥有一个包含MetaType类型的多个Meta记录的预订记录.我认为hasManyThrough可能已经解决了这个问题,但现在我想,也许这不是最好的方法.
在我的预订模型中,我有
public function bookingmeta() {
return $this->hasMany('bookingmeta','booking_id');
}
public function bookingmetatype() {
return $this->hasManyThrough('bookingmetatype','bookingmeta','booking_id','bookingmetatype_id');
}
Run Code Online (Sandbox Code Playgroud)
但是这无法生成正确的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)
Run Code Online (Sandbox Code Playgroud)
而我真正想要实现的是
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)
Run Code Online (Sandbox Code Playgroud)
如果有人能指出我正确的方向,我真的很感激.谢谢.
Jar*_*zyk 33
hasManyThrough根本不是这样的.它只适用于这样的关系:
A hasMany/hasOne B, B hasMany/hasOne C, then A hasManyThrough C (through B)
Run Code Online (Sandbox Code Playgroud)
你在这里有一个多对多(belongsToMany),meta作为数据透视表.
所以你可以这样做(假设meta是表名,Booking和MetaType是模型):
// Booking model
public function meta()
{
return $this->belongsToMany('MetaType', 'meta', 'booking_id', 'metatype_id')
->withPivot([ ARRAY OF FIELDS YOU NEED FROM meta TABLE ]);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以访问所有关联的MetaType:
$booking->meta; // collection of MetaType models
Run Code Online (Sandbox Code Playgroud)
像这样查询(急切加载):
$booking = Booking::with(['meta' => function ($q) {
// query related table
$q->where('someFieldOnMetaTypeTable', 'someValue')
// and / or pivot table
->wherePivot('someFieldOnMetaTable', 'anotherValue');
}])->first();
Run Code Online (Sandbox Code Playgroud)
或者在相关表上设置约束来过滤预订:
$booking = Booking::whereHas('meta', function ($q) {
// query related table
$q->where('someFieldOnMetaTypeTable', 'someValue')
// and / or pivot table
->where('meta.someFieldOnMetaTable', 'anotherValue');
})->first();
Run Code Online (Sandbox Code Playgroud)
注意:wherePivot仅在您急切加载关系时才有效,因此您无法在whereHas关闭时使用它.
| 归档时间: |
|
| 查看次数: |
14389 次 |
| 最近记录: |