我有表格,用户,个人资料,联系人。 1位用户有1个个人资料,1个个人资料有很多联系人,我想获取包含过滤后的联系人和所选列的个人资料(我不希望获得所有列)。我在下面编码成功了
UserController.php
$profile = $user->with(['profile.emails', 'profile.phones'])->first();
User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
Profile.php
public function emails()
{
return $this->hasMany(Contact::class)
->where('type', 'email');
}
public function phones()
{
return $this->hasMany(Contact::class)
->where('type', 'phone');
}
这样的结果数据
{
"username": "user",
"email": "user@mail.com",
"profile": {
"first_name": "Alex",
"last_name": "Ariana",
"emails": [
{
"id": 1,
"profile_id": 1,
"type": "email",
"prefix": "Personal",
"value": "alex@mail.com",
"is_primary": 0,
},
{
"id": 2,
"profile_id": 1,
"type": "email",
"prefix": "Business",
"value": "business@mail.com",
"is_primary": 1,
}
],
"phones": [
{
"id": 3,
"profile_id": 1,
"type": "phone",
"prefix": "45",
"value": "564637345345",
"is_primary": 1,
}
]
}
}
但随后我在这种关系上添加选择
public function emails()
{
return $this->hasMany(Contact::class)
->select([DB::raw('IFNULL(prefix, "Email") AS type'), 'value AS url', 'is_primary'])
->where('type', 'email');
}
public function phones()
{
return $this->hasMany(Contact::class)
->select(['prefix', 'value AS number', 'is_primary'])
->where('type', 'phone');
}
然后我得到了这样的空联系人数据 {
"id": 1,
"username": "user",
"email": "user@mail.com",
"profile": {
"first_name": "Alex",
"last_name": "Ariana",
"emails": [ ],
"phones": [ ]
}
}
为什么会发生这种情况?如果我通过hasManyThrough
从用户那里访问了它,但是当我使用hasMany
时,它为空。