有4张表:
-
bundles
: 身份证号、姓名
-
products
: 身份证号、姓名
-
prices
: 身份证号、姓名
-
bundle_product
:id、bundle_id、product_id、price_id
有3种型号:
A Product
has a Price
当在一个Bundle
。我想拥有一切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, 我想要价格 型号。有没有办法从枢轴预加载价格(使用预加载)?
当前接受的答案偏离了原始数据结构。
我创建了一个包,它可以帮助您实现您想要的,并且它还保留了原始的数据结构。请在这里阅读我的媒体故事:https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a 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);
}
}
确保你使用了这个特质AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait
in the Product
模型,因为它是belongsToMany关系中的相关模型。这让我们能够立即加载枢轴关系。
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Product extends Model
{
use EagerLoadPivotTrait;
}
然后像这样急切地加载它:
$bundle = Bundle::with('products.pivot.price')->first();
$price = $bundle->products->first()->pivot->price;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)