我有兩張桌子。客戶和地址。表的關系是一個 CUSTOMER 可以有多個 ADDRESSES。因此,我想要查詢的結果是獲取客戶串列和一個最新地址
ADDRESS TABLE
id : 1
city:"cebu"
zip_code:"600"
cus_id:1
id:2
city:"mandaue"
zip_code:"6001"
cus_id:1
CUSTOMER TABLE
id: 1
name:"JOHN DOE"
我想得到客戶“JOHN DOE”和 ID 為“2”的地址
我正在使用 laravel 查詢生成器
uj5u.com熱心網友回復:
你可以在 laravel 中使用 Eloquent ORM。
Eloquent : 你必須在你的客戶模型中設定
Class Customer(){
public function address()
{
return $this->hasMany(Address::class, 'cuss_id', 'id')->latest();
}
在您的地址模型中:
Class Address(){
public function customer()
{
return $this->belongsTo(Customer::class, 'id', 'cuss_id')
}
然后在您的控制器中,您可以呼叫模型:
$data = Customer::with('address')->get();
uj5u.com熱心網友回復:
如果您只想獲得一個最新的地址,您可以使用hasOne相同的:
// Customer model relation
public function lastestAddress()
{
return $this->hasOne(Address::class, 'customer_id')->orderBy('id', 'desc');
}
和
$model = Customer::with('lastestAddress')
uj5u.com熱心網友回復:
因此,您有兩個表:customers和addresses,具有“一個客戶可以有多個地址”的關系。
在 Laravel 中,我們通常使用 Eloquent模型來查詢資料庫。所以要獲取一個客戶及其所有地址,我們必須首先對資料庫進行建模;每個表都有自己的 Eloquent 模型。(請參閱檔案中的詳細資訊。)
class Address extends Model
{
// although empty for now, this class definition is still important
}
class Customer extends Model
{
/**
* Get the latest address.
*/
public function currentAddress()
{
return $this->hasOne(Address::class, 'cus_id')->latestOfMany();
}
}
在Customer模型中,我們的currentAddress()方法定義了一個Customer實體如何與這些實體相關聯Address。
就像我們在說,
“一個客戶可能有很多
Addresses。只要得到一個是 . 的latestOfMany。這就是我們將如何獲得客戶的currentAddress.
現在我們已經設定了必要的 Eloquent 模型,我們可以查找 John Doe 和他的當前地址。
$johnDoeId = 1;
// query the database for customer 1, including its current address
$johnDoe = Customer::with('currentAddress')->find($johnDoeId);
$johnDoe->currentAddress; // ?? John's latest address, at Mandaue
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/492257.html
上一篇:如何在mysql中更改日期格式
