我正在使用API Laravel为苹果指定其指定的属性(例如颜色)。我使用join来检索与指定品牌相关的苹果。但它不会检索具有自己指定属性的苹果,这些属性在另一个数据库和模型中定义。
public function index(Brand $brand)
{
$apples = Apple::join('brands', 'brand_id', 'brands.id')->where('brand_id', $brand->id)->get();
return returnSuccessfulResponse(
trans('api.response.successful.index'),
Resource::collection($apples)
);
}
Apple型号:
public function brand()
{
return $this->belongsTo(Brand::class);
}
public function appleProperties()
{
return $this->hasMany(AppleProperty::class);
}
资源:
return [
'id' => $this->brand->id,
'name' => $this->brand->name,
'apple-properties' => $this->appleProperties,
];
路线:
Route::apiResource('brands/{brand}/apples', 'AppleController');
它不是检索appleProperties
。我不明白这个理由!
在查询中使用join()方法时,建议也使用select(),这样就不再模糊您引用的表。在您的代码中,查询可能是这样的:
$apples = Apple::join('brands', 'brand_id', 'brands.id')->select('apples.*')->where('brand_id', $brand->id)->get();