gpt4 book ai didi

javascript - Laravel 连接多个表来获取数据

转载 作者:行者123 更新时间:2023-11-28 03:19:11 26 4
gpt4 key购买 nike

在我的场景中,我有 3 个表。客户、服务和 services_info。

客户表:

id |名字 |姓氏......等等

服务表:

id |服务 ID

services_info:

id |类别 |服务 |预计时间

我想要获取加入这些表的客户服务信息。一个客户有很多服务。所以我创建了 customer_service 表,其中包含客户表和服务表的外键,但它只有服务 ID,服务信息位于 service_info 表中。我如何加入这些表来获取每个客户的服务信息?我正在使用 laravel 5.8,而且我是新手。帮助我,提前致谢。

最佳答案

您应该添加一个customer_has_services

id|customer_id|service_id|created_at|updated_at

应用程序/模型/Customer.php:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Service;

class Customer extends Model {
...
public function services() {
return $this->belongsToMany( Service::class, "customer_has_services ", "sevice_id", "customer_id" );
}
}
?>

应用程序/模型/Service.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Customer;

class Service extends Model {
...
public function customers() {
return $this->belongsToMany( Customer::class, "customer_has_services ", "customer_id", "sevice_id" );
}
/**
* Get the phone associated with the user.
*/
public function info() {
return $this->hasOne( ServiceInfo::class, "id", "service_id" );
}
}
?>

应用程序/Http/Controllers/CustomerController.php

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Customer;

class CustomerController extends Controller {
public function index() {
$customers = Customer::with( "services.info" )->get();
foreach( $customers as $customer ) {
foreach( $customer[ "services" ] as $service ) {
echo $service[ "info" ][ "sevice" ];
}
}
}
}
?>

引用https://laravel.com/docs/5.8/eloquent-relationships .

客户和服务应该是多对多的。服务和服务信息应该是一对一的。

关于javascript - Laravel 连接多个表来获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com