我正在使用带有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
的位置是与成员表相关的数据,但我只需要内部关系数据(伙伴或访客数据)。对于intance,如果我Member::find(1)->partner
我得到的伙伴数据没有成员表的东西。 是否可以通过热切加载或Laravel中的其他方法执行此类操作?
我知道我可以操作并迭代输出并只保留必要的数据,但我只想知道是否可以在不进行更多查询或进行大量循环的情况下进行。
任何提示,帮助或评论都会有用。
答案 0 :(得分:0)
尝试在模型类中使用$visible
和$hidden
数组。
来自文档:
有时您可能希望限制其中包含的属性 您的模型的数组或JSON表单,例如密码。为此,请添加 隐藏属性定义到您的模型:
隐藏数组或JSON转换的属性
class User extends Eloquent {
protected $hidden = array('password');
}
或者,您可以使用visible属性来定义 白名单:
protected $visible = array('first_name', 'last_name');