我正在尝试访问one to many
逆关系的数据。
我的经销商模型
public function users()
{
return $this->hasMany(User::class);
}
我的用户模型:
public function dealer(){
return $this->belongsTo(Dealer::class,);
}
我尝试使用以下方法从经销商处检索数据:
$variable = \Auth::user()->dealer()->get();
执行dd($variable)
时具有以下数组。
Illuminate\Database\Eloquent\Collection {#1291 ▼
#items: array:1 [▼
0 => App\Dealer {#1293 ▼
#guard: "dealer"
#fillable: array:5 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "dealers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:34 [▶]
#original: array:34 [▶]
#changes: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}
我要访问的信息位于#attributes下。
如果我使用$dealer = \Auth::user()->dealer()->get()->toArray();
,则会得到如下数组。
array:1 [▼
0 => array:32 [▼
"id" => 1
"admin_id" => 1
"name" => "Example"
"contact" => "Cheree"
"email" => "cheree@example.co.za"
"access" => "Standard"
如何访问#attributes中的数据?
答案 0 :(得分:0)
您在另一个array
中有一个array
。因此,您有一个数组数组。要访问内部数组元素,您首先必须从外部数组中选择。
因此,您必须致电:$varaible[0]['name']
这意味着您将获得$variable
的第一个元素(例如0),它是一个数组,然后从该数组中获得键为“名称”的元素。
@edit
您只需删除->get()
,即可通过调用Auth::user()->dealer
或Auth::user()->dealer()->first()