php - Laravel 获取 Eloquent 构建器实例的属性
问题描述
我无法访问供应商名称或供应商描述的属性值。此调用函数$vendor->vendorname;
将返回错误
Property [vendorname] does not exist on the Eloquent builder instance.
如何访问 vendorname 或 vendordescription 的属性值?谢谢
网站中的模型返回对象
Illuminate\Database\Eloquent\Builder {#1330 ▼
#query: Illuminate\Database\Query\Builder {#381 ▶}
#model: App\Models\Vendor {#1349 ▼
#fillable: array:2 [▶]
#connection: "mysql"
#table: "vendors"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:5 [▼
"id" => 2
"created_at" => "2021-08-01 11:48:20"
"updated_at" => "2021-08-01 11:48:20"
"vendorname" => "cloyad"
"vendordescription" => "cloyad"
]
#original: array:5 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
#eagerLoad: []
#localMacros: []
#onDelete: null
#passthru: array:19 [▶]
#scopes: []
#removedScopes: []
}
App/Http/Controllers 中的控制器功能
public function index(User $user, Request $request){
//Retrieve the favroutie listings from user
$fav = User::with('posts')->get()->where('id', $user->id);
//dd($fav);
$favArray = [];
foreach($fav as $t){
foreach($t->posts as $p){
$collection = collect();
$collection->push($p);
$vendor = Vendor::with('posts')->first()->where('post_id', $p->id);
dd($vendor->vendorname);
array_unshift($favArray, $p);
}
}
}
使用数据透视表从两个模型中获取的解决方案
public function index(User $user, Request $request){
//Retrieve the favroutie listings from user
$fav = User::with('posts')->get()->where('id', $user->id);
//dd($fav);
$favArray = [];
foreach($fav as $t){
foreach($t->posts as $p){
$collection = collect();
$collection->push($p);
$vendor = Vendor::with('posts')->get();
foreach($vendor as $v){
foreach($v->posts as $vv){
if($vv->id == $p->id){
$collection->push($v);
}
}
}
array_unshift($favArray, $collection);
}
}
解决方案
您可以在进入 foreach 循环之前查询所有需要的供应商,然后在内存中搜索返回的项目。
foreach($fav as $t){
$vendors = Vendor::with('posts')->whereIn('post_id', data_get($t->posts, '*.id', []))->get();
foreach($t->posts as $p){
$collection = collect();
$collection->push($p);
$vendor = $vendors->where('post_id', $p->id)->first();
dd($vendor->vendorname);
array_unshift($favArray, $p);
}
}
推荐阅读
- yaml - 在 YAML 中存储特殊符号
- arrays - 日期范围之间的最小值
- go - 我可以在 go 的 if 范围内声明两个变量吗?
- javascript - 如何让玩家同时朝两个不同的方向移动?
- python - 尝试将 BufferedReader 上传到 Python 中的 Azure Blob 存储时,base64 编码的字符串无效
- spring-kafka - 创建消费者绑定失败;30 秒后重试:BinderException
- php - WP All Import - 在属性项中从函数编辑器映射值
- r - 理解 R 中的警告信息
- c# - 我可以知道谁与我的 TCP 服务器断开连接吗?C#
- c# - 异步合理性检查会导致出现竞争条件吗?