我如何 select 来自查询生成器中不同表的值 Laravel

How do I select a value from different tables in Query Builder Laravel

所以我正在尝试从 mysql table 到 excel 获取“promo_type”值。但是我需要使用另一个 table 来获得这个“promo_type”的值。

所以这是主要的 table 预订,其中包含促销代码的价值。如下所示,用户的促销代码为“1000”。 预订 Table

现在在另一个 table 中,这是制作和保存促销代码的地方。

促销代码table

但我需要访问“promo_type”变量才能将其导出到 excel。我怎样才能做到这一点?我正在考虑从预订 table 中选择促销代码的值并将其与促销代码 table 进行比较,然后选择“promo_type”列。但我不知道如何将其转换为查询构建器语法。

这是我用来将数据导出到 excel 的代码。所以我需要 return 以 suitable 的方式将值导出到 excel.

public function collection()
{

    return Booking::select(
        'id',
        'place_id',
        'payer_name',
        'user_fullname',
        'user_email',
        'user_phone',
        'user_no_of_guest',
        'user_no_of_babies',
        'user_checkin',
        'user_checkout',
        'is_approved',
        'user_promo',
        'user_payment_type',
        'user_booking_tracking_id',
        'created_at',
        Booking::raw('(created_at +  INTERVAL 2 HOUR) AS created_at'),
        'paid_amount'
    )
        ->whereRaw('"' . $this->date . '" between `user_checkin` and `user_checkout`')
        ->get();
}



public function headings(): array
{
    return [
        'ID',
        'Place ID',
        'Payer Name',
        'Full Name',
        'Email',
        'Phone',
        'Number of adults',
        'Number of babies',
        'Arrival Time',
        'Checkout Time',
        'Approval',
        'Promo',
        'Payment Type',
        'Tracking Id',
        'Created At',
        'Total Amount',
    ];
}

我认为您的 table 关系有问题。根据您的概念,而不是使用 promo_code 列,您应该在促销代码 table(外键)中添加引用 idpromo_code_id 列。

在您的模型中,您可以利用与 Booking 模型的 Eloquent hasOne() 关系,例如

class Booking extends Model
{
    public function promoCode()
    {
        return $this->hasOne(PromoCode::class, 'id', 'promo_code_id');
    }

    ...

}

PromoCode 是促销代码 table 的模型。

然后,您可以使用Eloquent关系

获取Promo Code数据
public function foo()
{
    $promoCode = Booking::first()->promoCode;
}

我不会为此使用 select,我会一直使用 Eloquent 方法。这是更务实的方式,也是预期的方式。

您需要有关系才能执行此操作,将 PromoCode 关系添加到 Booking.php class。

class Booking
{
    public function promoCode()
    {
        return $this->belongsTo(PromoCode::class, 'user_promo', 'promocode');
    }
}

现在您可以使用 Laravel Excel 中的函数来正确查询和映射您的数据。

public function collection()
{
    return Booking::whereRaw('"' . $this->date . + '" between `user_checkin` and `user_checkout`')->get();
}

public function map($booking): array
{
    return [
        // your other fields
        $booking->promoCode->promo_type,
    ];
}