【发布时间】:2019-07-01 22:18:06
【问题描述】:
我是 Laravel 的新手,需要编写一个简单的后端 API。 我做错了,我不知道是什么,因为我从供应商表和空数组 payments:[] 中获取了一些数据。
我正在尝试从两个相关表 - PAYMENTS 和 SUPPLIERS 中获取所有数据。 PAYMENTS 表中的 SUPPLIERS_ID 与 SUPPLIERS 中的 ID 是一对多的关系。这里我给你一个图形表示:
这是我的代码:
Suppliers.php 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments');
}
}
Payments.php 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->hasOne('App\Suppliers');
}
}
PaymentsController.php
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PaymentsController extends Controller
{
public function index()
{
$payments = Suppliers::with('payments')->get();
return response($payments, Response::HTTP_OK);
}
}
我得到以下答案:
[{"id":1,"name":"Ekonaft","adress":"33-100 Tarnow ","email":"ekonaft@gmail.com","payments":[]},
{"id":2,"name":"Orlen","adress":"Ares testowy","email":"email@email.pl","payments":[]}]
我做错了什么,我在每个对象的末尾得到一个空数组 payments:[ ]?
【问题讨论】: