我有一个具有相关关系的Mailgroup模型,如下所示:
$communicationTypes = $mailgroup->communicationTypes->toArray();
这将返回:
array (size=3)
0 =>
array (size=3)
'id' => int 9
'mailgroup_id' => int 16
'communication_type' => string 'a' (length=1)
1 =>
array (size=3)
'id' => int 10
'mailgroup_id' => int 16
'communication_type' => string 'b' (length=1)
2 =>
array (size=3)
'id' => int 11
'mailgroup_id' => int 16
'communication_type' => string 'c' (length=1)
我的目标是得到这个:
array (size=3)
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
现在,我尝试了以下操作,但所有操作均导致错误。
$communicationTypes = $mailgroup->communicationTypes()->communication_type->toArray();
$communicationTypes = $mailgroup->communicationTypes()->pluck('communication_type')->toArray();
答案 0 :(得分:0)
最简单的方法是遍历结果数组并从中创建一个新数组。在不考虑最佳实践的情况下或者是否应该首先将集合转换为这种形式的数组,而不是回答以下问题:
$newArray = [];
foreach ($communicationTypes as $key => $item) {
$newArray[$key] = $item['communication_type'];
}