拉拉维尔 - 访问关系属性



我需要访问电子邮件值;它从一个关系hasOnce((,
这是dd($this->order_details(

IlluminateDatabaseEloquentCollection {#2322 ▼   #items: array:1 [▼
0 => AppOrder {#2327 ▼
#hidden: array:1 [▶]
#connection: "mysql"
#table: "orders"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▶]
#original: array:12 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: array:1 [▶]
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"user" => AppUser {#2356 ▼
#dispatchesEvents: array:1 [▶]
#fillable: array:3 [▶]
#hidden: array:9 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:20 [▼
"id" => 36
"email" => "email@gmail.com"
"password" => "$2y$10$f.u7MO6ZZ4GBf1uaabiF9OXerh0SR7JzUV9M5PGI1IG1xFATkeTSG"
"name" => "NAME"
"surname" => "SURNAME"
"phone" => "+39331199222"
"confirm_code" => 111111
"confirm_code_date" => "2020-06-01 18:17:42"
"confirm_tries" => 0
"city_id" => 5662
"stripe_customer_id" => "cus_HPVN1YJE0wjHtm"
"status" => "ACTIVE"
"is_admin" => 1
"price_list_id" => 1
"wallet" => 99852.6
"last_login_at" => "2020-06-05 11:49:32"
"remember_token" => null
"created_at" => "2020-06-01 18:17:42"
"updated_at" => "2020-06-08 16:33:12"
"deleted_at" => null

当我尝试使用它时:$this->order_details->user->email
我回来了:

属性 [user] 在此集合实例上不存在。

我不知道哪个是我的错误,也不知道有什么问题, 与$this->order_details->user[0]->email结果是一样的

您正在尝试访问集合中不存在的对象。

$this->order_details是一个Collection

您需要访问第一个order,然后才能访问user

$firstOrder = $this->order_details->first();
$user = $firstOrder->user;
$email = $user->email;
// Or:
$email = $this->order_details->first()->user->email;

当然,您也可以迭代集合中的订单,但现在我假设您只需要第一个订单。

最新更新