有4个表:
bundles
: id, nameproducts
: id, name价格
: id, namebundle_product
: id, bundle_id, product_id, price_id
有3种模式:
bundle
产品
价格
Product
在 Bundle
中时有一个 Price
。我想要所有 bundles
及其相关的 products
和相关的 price
。 我可以得到所有的 bundles 及其产品和价格 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;
但我不想要价格 ID,我想要价格模型。有什么方法可以从枢轴预加载价格(使用预加载)?
最佳答案
当前接受的答案偏离了原来的数据结构。 我创建了一个包,它可以帮助你实现你想要的,并且它保持了原始的数据结构。请在这里阅读我的媒体故事:https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a
首先,创建您的自定义数据透视模型并在数据透视模型上定义关系,在您的情况下:
use Illuminate\Database\Eloquent\Relations\Pivot;
class BundleProduct extends Pivot
{
public function price()
{
return $this->belongsTo(Price::class);
}
}
然后在关系中使用枢轴模型:
class Bundle extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)
->withPivot('price_id') // this is needed to query the relation `price`
->using(BundleProduct::class);
}
}
确保在 Product
模型中使用特征 AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait
,因为它是 belongsToMany 关系中的相关模型。这让我们能够预先加载枢轴关系。
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Product extends Model
{
use EagerLoadPivotTrait;
}
然后像这样急切加载它:
$bundle = Bundle::with('products.pivot.price')->first();
$price = $bundle->products->first()->pivot->price;
关于php - 预加载 : Use `with` on pivot with eloquent relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572231/