![](/img/trans.png)
[英]How to get related data from two tables while there are two Foreign keys related to One Primary key in Laravel Framework
[英]How to get all data from two related tables in Laravel [one to many]
我在Laravel中很陌生,需要編寫一個簡單的后端API。 我做錯了什么,我不知道怎么辦,因為我從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":[]}]
我做錯了什么,我在每個對象的末尾都得到了空數組付款:[] ?
嘗試付款的逆向關系
belongsTo = has a foreign key to another table
舉個例子
這是您可以從“付款”中訪問供應商的方式
<?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
像貝爾一樣改變你的關系
Suppliers.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');
}
}
Payments.php模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo(App\Suppliers::class, 'suppliers_ID', 'id');
}
}
然后再試一次..... :)
由於未匹配的表關系鍵名稱,您將得到空的付款數組:[] 。
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
讓我知道您是否仍然遇到相同的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.