我有一个雄辩模型AppListing
,belongsTo
AppProduct
public function product()
{
return $this->belongsTo(Product::class);
}
在列表控制器中,我试图从产品表中获得具有2列(name
,keywords
)的特定列表。
public function readListing(Request $request, $listingId)
{
$query = Listing::query();
$item = $query->with(['product' => function (Builder $query) {
return $query->select(['name', 'keywords']);
}])->findOrFail($listingId);
return response()->json($item->toArray(), 200);
}
我得到这个错误:
TypeError参数1传递给AppHttpControllersAPIListingController::AppHttpControllersAPI{closure}()必须是一个实例IlluminateDatabaseEloquentBuilder,实例IlluminateDatabaseEloquentRelationsBelongsTo给出,在vendorlaravelframeworksrcIlluminateDatabaseEloquentBuilder.php中调用
其中第580行是
$item = $query->with(['product' => function (Builder $query) {
当我删除类型声明从像这样的行
$item = $query->with(['product' => function ($query) {
我得到一个结果,但它不包括产品表中的2列(name
,keywords
)。
{
id: 1,
product_id: 1,
listing_price: 10,
actual_price: 5,
in_stock: 1,
listing_date: null,
delisting_date: null,
created_at: "2021-02-24T12:33:48.000000Z",
updated_at: "2021-02-24T13:45:25.000000Z",
deleted_at: null,
category: "Fruits",
category_id: 2,
description: "Rem laudantium aut",
image_urls: [
".../storage/products/February2021/CF3nzhmc0RXevSWdOJcd.jpg",
".../storage/products/February2021/oBtXf5kBjkAyrazuFDyu.jpg",
".../storage/products/February2021/GfpaGxSoGLA2FBqGrcDX.jpg"
],
image_medium_urls: [
".../storage/products/February2021/CF3nzhmc0RXevSWdOJcd-medium.jpg",
".../storage/products/February2021/oBtXf5kBjkAyrazuFDyu-medium.jpg",
".../storage/products/February2021/GfpaGxSoGLA2FBqGrcDX-medium.jpg"
],
image_small_urls: [
".../storage/products/February2021/CF3nzhmc0RXevSWdOJcd-small.jpg",
".../storage/products/February2021/oBtXf5kBjkAyrazuFDyu-small.jpg",
".../storage/products/February2021/GfpaGxSoGLA2FBqGrcDX-small.jpg"
],
thumbnail_url: ".../storage/products/February2021/CF3nzhmc0RXevSWdOJcd-small.jpg",
product: null
}
为什么类型声明会导致问题,我如何让它从相关表中选择这两列?
您需要在您的案例中包含foreign_key
listing_id
$query = Listing::with(['product' => function ($query) {
// add listing_id
return $query->select(['listing_id', 'name', 'keywords']);
}])
->findOrFail($listingId);
laravel docs
在使用此特性时,您应该始终包含id列和任何相关的外键列列表中的列,您希望检索。