php – Laravel hasManyThrough
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – Laravel hasManyThrough,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2250字,纯文字阅读大概需要4分钟。
内容图文
![php – Laravel hasManyThrough](/upload/InfoBanner/zyjiaocheng/700/2bc4d0f906714e67927aac01db5264fd.jpg)
我正在努力通过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
我想要得到的是一个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');
}
但是这无法生成正确的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)
如果有人能指出我正确的方向,我真的很感激.谢谢.
解决方法:
hasManyThrough根本不是.它只适用于这样的关系:
A hasMany/hasOne B, B hasMany/hasOne C, then A hasManyThrough C (through B)
你在这里有多对多(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 ]);
}
然后,您可以访问所有关联的MetaType:
$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();
注意:wherePivot仅在您急切加载关系时才起作用,因此您无法在whereHas闭包中使用它.
内容总结
以上是互联网集市为您收集整理的php – Laravel hasManyThrough全部内容,希望文章能够帮你解决php – Laravel hasManyThrough所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。