如何从Laravel中的两个相关表中获取所有数据[一对多]

时间:2019-02-07 17:55:03

标签: php laravel

我在Laravel中还很陌生,需要编写一个简单的后端API。 我做错了什么,我不知道怎么办,因为我从Suppliers表和空数组 payments:[] 中获取了一些数据。

我正在尝试从两个相关的表-PAYMENTS和SUPPLIERS中获取所有数据。 PAYMENTS表中的SUPPLIERS_ID与SUPPLIERS中的ID是一对多的关系。在这里,我给您一个图形表示:

a busy cat

这是我的代码:

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:[]

3 个答案:

答案 0 :(得分:1)

尝试付款方面的逆向关系

belongsTo = has a foreign key to another table

引用示例

  

Should i use belongsTo or hasOne in Laravel?

这是您可以从“付款”中访问供应商的方式

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payments extends Model
{
   public function suppliers()
   {
      return $this->belongsTo('App\Suppliers'); 
  }
}

这是来自供应商的付款

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Suppliers extends Model
{
   public function payments()
   {
      return $this->hasMany('App\Payments','suppliers_ID','id'); 
   }
}

此外,请确保ID在输出中可见(如果ID被隐藏,则laravel无法处理该关系)。如果要使用hasOne

,也可以在关系上指定键

编辑:在关系中添加键名称,您的fk命名为capslock

答案 1 :(得分:0)

像bel那样改变你的关系

Suppliers.php模型

array([[ 3,  4],
   [ 5,  4],
   [ 2,  8],
   [ 4,  8],
   [56, 12],
   [ 2, 15],
   [ 1, 23],
   [ 7, 29]])

Payments.php模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Suppliers extends Model
{
   public function payments()
   {
      return $this->hasMany(App\Payments::class, 'suppliers_ID', 'id'); 
   }
}

然后重试.....:)

答案 2 :(得分:0)

由于表关系键名称不匹配,您将得到空的付款数组:[]

Please, make few changes in both relational function.

public function payments() 
{

    //return $this->hasMany('App\Model', 'foreign_key', 'local_key');
    return $this->hasMany('App\Payments', 'suppliers_id'); 

}

public function suppliers()
{

    //return $this->belongsTo('App\Model', 'foreign_key', 'other_key');
    return $this->belongsTo('App\Suppliers', 'suppliers_id'); 

}

您可以直接从Laravel文档中了解有关口才关系的更多信息,以更好地理解。 https://laravel.com/docs/5.7/eloquent-relationships#one-to-many

让我知道您是否仍然遇到相同的错误。