我正在使用带有 MySQL 的 Laravel 4 并使用关系方法来访问相关表的数据。我有以下相关表格:
团队表:
id INT
partnet_id INT -- Related many-to-one with partner table
name VARCHAR(50)
合作伙伴表:
id INT
name VARCHAR(50)
-- more data about only to partners
客人桌:
id INT
name VARCHAR(50)
-- more data about only to guests
和成员表:
id INT
partner_id INT -- Related many-to-one to partner table
guest_id INT -- Related many-to-one to guest table
team_id INT -- Related many-to-one to team table
所以,我想让一个团队(或所有团队)与他们的成员一起使用他们与客人或合作伙伴的相关数据。
输出应该是这样的:
{
"id": 1,
"partner": {
"id": 1,
"name":"Hello world",
"partner_number":1111,
"handicap":12
},
"name":"my team,
"members": [
{
"id": 1,
"name":"Hello world",
"partner_number":1111,
"handicap":12,
"type": "partner"
},
{
"id": 2,
"name": "Cat Kitten",
"partner_number":2222,
"handicap":12,
"type": "partner"
},
{
"id": 3,
"name": "Bruce Wayne",
"partner_number":3333,
"handicap":10,
"type": "partner"
},
{
"id": 1,
"name": "The Joker",
"idcard":21841933,
"handicap":10,
"type": "guest"
}
]
}
我尝试通过以下方式获得该输出:
$teams = Team::find(1);
$teams->load('partner', 'member.partner', 'member.guest');
有了它,我得到了所需的数据,但有了我并不真正想要/不需要的东西:
Array
(
[id] => 2
[partner_id] => 2
[name] => 'my team'
[partner] => Array
(
[id] => 2
[name] => Batman Batman
[partner_number] => 2222
[handicap] => 8
)
[members] => Array
(
[1] => Array
(
[id] => 5 // I don't need this
[team_id] => 2 // I don't need this
[partner_id] => 3 // I don't need this
[guest_id] => // I don't need this
[partner] => Array
(
[id] => 3
[name] => Amazing Spiderman
[partner_number] => 3333
[handicap] => 12
)
[guest] => // I don't need this
)
[2] => Array
(
[id] => 6 // I don't need this
[team_id] => 2 // I don't need this
[partner_id] => // I don't need this
[guest_id] => 1 // I don't need this
[partner] => // I don't need this
[guest] => Array
(
[id] => 1
[name] => Eddard Stark
[idcard] => 2139823
[handicap] => 21
)
)
)
)
评论的地方// I don't need this
是与成员表相关的数据,但我只需要内部关系数据(合作伙伴或访客数据)。例如,如果我这样做,Member::find(1)->partner
我会得到没有成员表内容的合作伙伴数据。是否可以在 Laravel 中使用急切加载或其他方法来做类似的事情?
我知道我可以对输出进行操作和迭代,只保留必要的数据,但我只想知道是否可以不进行更多查询或进行繁重的循环。
任何提示、帮助或评论都会很有用。