我正在使用 laravel 8。我嘗試獲取具有多對多關系的資料,但給我相關表的空資料
這是資料庫

訂單模式
public function products()
{
return $this->belongsToMany(Product::class);
}
產品型號
public function orders(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Order::class);
}
并獲取查詢是
$orders = Order::query()->with("products")->get();
結果

我也檢查
$orders = Order::query()->has("products")->get();
給我同樣的結果
uj5u.com熱心網友回復:
首先,如果您正在編輯這樣的查詢,它將起作用
$orders = Order::fist();
$orders->products;
為什么?因為資料透視表。
什么是資料透視表?讓我解釋。
當您使用many-to-many關系時,您必須定義一個中間表,如您的表:order_prodcts。所以 Laravel 在這里提供了一些非常有用的與這個表互動的方法。
所以這是一個database結構:
orders:
- id
- title
products:
- id
- title
order_product:
- id
- title
串列中的最終表:order_product稱為pivot表
讓我們舉個例子
假設我們的Order模型有很多Product與之相關的模型。訪問此關系后,我們可以使用您在模型上定義的關系方法訪問中間表,例如:
1-你的Product模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//some code
public function orders()
{
return $this->belongsToMany(Product::class);
}
}
2-你的Order模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
//some code
public function produtc()
{
return $this->belongsToMany(Order::class);
}
}
Here each Product model we retrieve is automatically assigned a relation method. This relation method contains a model representing the intermediate order_product table.
SO here try to get you orders with your products
public function index()
{
$orders = Order::get();
dd($orders->products); //Laravel will handel the pivot and will return your order products
}
Now, there are several things to mention when using pivot.
Pivot table fields by default should be only two fields: foreign key to each of the tables
order_idproduct_idName of the pivot table should consist of
singularnamesNames should be arranged in
alphabeticalorder in your caseois first ofpso your table will be calledorder_product
Finally Thank you for finishing the read I hope you gained any information from this answer
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/422366.html
標籤:
