我很难理解拉威尔的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 的模型,它允许我有一个单一的预订记录和多个元类型的元记录.我以为hasManyThrough可能已经解决了这个问题,但现在我想这可能不是最好的办法.

In my booking model I have

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)

What you have here is a many to many (belongsToMany), with meta being the pivot table.

So you can do this (assuming meta is table name, Booking and MetaType are models):

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

Then you can access all associated MetaType:

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

query it like this (eager loading):

$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();

Note: wherePivot works only when you eager load the relationship, so you can't use it in whereHas closure.

Laravel相关问答推荐

在postgres/mysqlс中,我可以定义基于json字段的唯一索引吗?

如何将用户对象绑定到中间件中的请求

Laravel:如何强制使用 HTTPS?

磁盘 [视频] 没有配置的驱动程序

Laravel 5 - ErrorException 无法打开流:权限被拒绝

静态密码在默认的 Laravel 用户工厂中是如何工作的?

Laravel 5.5 在迁移文件中设置整数字段的大小

为什么人们将 .env 放入 gitignore?

使用 ModelNotFoundException

调用未定义的函数 mb_strimwidth

在 Laravel 中将 Public 添加到assets资源路径

如何在没有 Artisan 的情况下运行 Laravel?

Http请求多浏览器的烦恼

如何使用外部图像生成 html div 的 screenshot截图?

Laravel 初学者的良好开端

Laravel Queue,Beanstalkd vs Database,有什么区别?

在 Laravel 5.4 中将文件存储在公共目录和存储中的区别

Laravel 5.4 Vue.JS 无法挂载组件:未定义模板或渲染函数

Laravel X-CSRF-Token 与 POSTMAN 不匹配

如何在脚本文件中使用 Laravel Blade?