PHP code example of ajcastro / eager-load-pivot-relations

1. Go to this page and download the library: Download ajcastro/eager-load-pivot-relations library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ajcastro / eager-load-pivot-relations example snippets


class Unit extends \Eloquent {
}
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Item extends \Eloquent
{
    // Use the trait here to override eloquent builder.
    // It is used in this model because it is the relation model defined in
    // Plan::items() relation.
    use EagerLoadPivotTrait;
    public function plans()
    {
        return $this->belongsToMany('Plan', 'plan_item');
    }
}
class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->using('PlanItem')
            // make sure to 

class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->withPivot('unit_id', 'qty', 'price')
            ->using('PlanItem')
            ->as('planItem');
    }
}

use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Plan extends \Eloquent
{
    use EagerLoadPivotTrait;
}

return Plan::with('items.planItem.unit')->get();

$plan = Plan::with('items.planItem.unit');
foreach ($plan->items as $item) {
    $unit = $item->planItem->unit;
    echo $unit->name;
}