dd 可以看到数据,但是无法读取,是为什么
上代码:
$user_result = Auth::user()->topicanswers->where('topic_id',$this->id);
dd($user_result);
结果:
Illuminate\Database\Eloquent\Collection {#842 ▼
#items: array:1 [▼
0 => App\Models\TopicAnswer {#869 ▼
#fillable: array:1 [▶]
#connection: "mysql"
#table: "topic_answers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▼
"id" => 1
"user_id" => 1
"topic_id" => 2
"result" => 2
"created_at" => "2020-02-29 01:19:33"
"updated_at" => "2020-02-29 01:19:35"
]
#original: array:6 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
继续,dd($user_result->result)
报错:
Property [result] does not exist on this collection instance. (View: D:\Didongni\App\idongni\resources\views\mobile\topics\index.blade.php)
这是为什么,为什么读取不到2
好,再继续,dd(collect($user_result))
,结果:
Illuminate\Support\Collection {#732 ▼
#items: array:1 [▼
0 => App\Models\TopicAnswer {#869 ▼
#fillable: array:1 [▶]
#connection: "mysql"
#table: "topic_answers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▼
"id" => 1
"user_id" => 1
"topic_id" => 2
"result" => 2
"created_at" => "2020-02-29 01:19:33"
"updated_at" => "2020-02-29 01:19:35"
]
#original: array:6 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
这下总可以了吧,但是dd(collect($user_result)->result)
依然报错:
Property [result] does not exist on this collection instance. (View: D:\Didongni\App\idongni\resources\views\mobile\topics\index.blade.php)
使用这2个方法可以直接访问属性获取相应的值,而你的代码实际用了 get() ,会返回一个数组。
试想一下,如果你返回了2条数据,你直接用
$user_result->result
应该显示哪条数据的result
值呢?