首页 > 解决方案 > 如何在 laravel 7 中创建 3 个表之间的关系?

问题描述

我在数据库中有三个表。第一个是“bookings”,包含一些列:id、customer_id 等。第二个是“customer”,包含 id、name、email 等。

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

ID object_id 元密钥 元值
1 1 cf_x4rMBfn3 1989 年 10 月 11 日
2 1 cf_x4rMBfb5 1234567
3 1 cf_x4rMB735

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

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”访问数据。我似乎无法弄清楚“bookings”表和“customer_meta”表之间的关系类型。我想通过包含 customer_id 的“预订”显示特定客户的所有行。

标签: phplaravellaravel-7table-relationships

解决方案


如果您设置了 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);
    }
}

推荐阅读