【发布时间】:2016-10-01 00:46:26
【问题描述】:
有4张桌子:
-
bundles:身份证,姓名 -
products:身份证、姓名 -
prices:身份证、姓名 -
bundle_product: id、bundle_id、product_id、price_id
有 3 种型号:
BundleProductPrice
Product 在Bundle 中时具有Price。我想拥有所有 bundles 及其关联的 products 和关联的 prices。 我可以获取所有包含其产品和价格 ID 的捆绑包:
// I created a Bundle Model with a products method
class Bundle extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('price_id');
}
}
// Then I call this in a controller
$all_bundles = Bundle::with('products')->get();
// Then I can get the price Id of the first product of the first bundle
$price_id = Bundle::with('products')->first()
->products()->first()
->pivot->price_id;
但我不想要 price id,我想要 price Model。有什么方法可以从枢轴预加载价格(使用 Eager Loading)?
【问题讨论】:
标签: php laravel laravel-5 eloquent