如何在laravel 7中的3个表之间创建关系?

问题描述

我在一个数据库中有三个表。 第一个是带有一些列的“预订”:id、customer_id 等。 第二个是“客户”,包括 ID、姓名、电子邮件等。

第三个是“customer_Meta”,带有 id、object_id(这是对“customer”表中 id 列的引用)、Meta_key 和 Meta_value。它包含有关客户的其他数据,如出生日期、护照号码、性别等。 此表中的每一行都是特定客户的不同条目,如下所示:

id object_id Meta_key 元值
1 1 cf_x4rMBfn3 10/11/1989
2 1 cf_x4rMBfb5 1234567
3 1 cf_x4rMB735 M

我在预订表和客户表之间创建了一对多关系。这是我的控制器中索引函数代码

public function index()
{
    
    $bookings = Booking::with('customer')->get();
   
    return view('bookings',[
        'bookings' => $bookings,]);

}

一切正常。我可以像这样在我的刀片文件显示数据:

<tbody>
    
        @foreach ( $bookings as $booking )
            <tr>
                <td>{{ $booking->id }}</td>
                <td>{{ $booking->start_date }}</td>
                <td>{{ $booking->customer->first_name }}</td>
                <td>{{ $booking->customer->last_name }}</td>
            </tr>
        @endforeach

    </tbody>

现在我想访问来自“customer_Meta”的数据。我似乎无法弄清楚“预订”表和“customer_Meta”表之间的关系类型。我想通过包含 customer_id 的“预订”显示特定客户的所有行。

解决方法

如果您设置了 customer 和 customer_meta 之间的关系,您应该可以像这样访问它

class Customer extends Model
{
    public function customerMeta()
    {
        return $this->hasMany(App\Models\CustomerMeta::class,'object_id','id');

    }
}


$bookings = Booking::with('customer','customer.customerMeta')->get();     
...
        
{{ $booking->customer->customerMeta->meta_key }}

如果您想直接从预订记录访问 customer_meta,您可以使用“有一个通过”或“有多个通过”关系 见https://laravel.com/docs/7.x/eloquent-relationships#has-one-through

这样您就可以直接从预订记录中访问 c​​ustomer_meta

class Booking extends Model 
{
    public function customerMeta()
    {
      return $this->hasOneThrough(App\Models\CustomerMeta::class,App\Models\Customer::class);
    }
}