【发布时间】:2021-08-04 21:31:52
【问题描述】:
我无法访问供应商名称或供应商描述的属性值。此调用函数$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);
}
}
【问题讨论】:
-
欢迎来到 SO。请在您的问题中添加您的 php 代码。
-
我已经在php代码中添加了,谢谢
-
$vendor = Vendor::with('posts')->where('post_id', $p->id)->first();你可以试试 -
谢谢,但它不起作用,因为“post_id”来自数据透视表。它需要获取它之前的所有项目并查询它。我自己已经想出了一个解决方案并编辑了我的问题。