php - 预加载 : Use `with` on pivot with eloquent relationship

标签 php laravel laravel-5 eloquent

有4个表:

  • bundles: id, name
  • products: id, name
  • 价格: id, name
  • bundle_product: id, bundle_id, product_id, price_id

有3种模式:

  • bundle
  • 产品
  • 价格

ProductBundle 中时有一个 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/

相关文章:

javascript - 使用jquery的PHP cURL下载进度

mysql - 使用 Laravel/Docker 备份和恢复 mysql 数据库

laravel - Laravel 中的 attributesToArray() 和 toArray() 有什么区别?

javascript - 如何向特定用户推送通知 Node + AngularJS + Laravel

php - 在 Laravel 5 中创建管理员区域界面的最佳实践

php - 需要有关构建无状态 Web 应用程序的信息

php - Firebase 与 php 中的 codeigniter 的连接

php - Symfony2 形式转 JSON 结构

php - DB::select 过程从输入请求返回空数组

Phpunit 在 Laravel 中测试具有部分 View 的表单时抛出错误