我正在學習 Laravel,需要獲取嵌套關系串列。我的外鍵似乎設定正確。
products->servers->configs
產品控制器
$products = Product::with('servers')->get();
產品型號
public function servers()
{
return $this->hasManyThrough(Config::class, Server::class);
}
我只得到一個配置的服務器串列。例如
products:{
id:1,
servers:[
ram:16gb //this is the config not the server
]
}
如何獲取產品內服務器內的配置串列?例如
products:{
id:1,
server:{
id:1,
name:'big server',
config:{
ram:16gb
}
}
}
uj5u.com熱心網友回復:
在產品模態使用hasMany方法
public function servers()
{
return $this->hasMany(Server::class);
}
在服務器模式使用hasMany(for many rows get)或hasOne(for single row get)方法
public function configs()
{
return $this->hasMany(Config::class);
}
public function config()
{
return $this->hasOne(Config::class);
}
現在ProuctController 看看如何獲??取嵌套關系資料
$products = Product::with('servers.configs')->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/514642.html
