简体   繁体   中英

Eager load related models in Laravel's Revisionable history

Using Laravel 5.4 and the VentureCraft/revisionable package.

I have 3 models: User , Company and Order .

The Order model implements the Revisionable trait:

namespace App\Models;

class Order extends Eloquent {
    use \Venturecraft\Revisionable\RevisionableTrait;

    // ...
}

The User model has a relationship with the Company model:

public function company() {
    return $this->belongsTo('App\Models\Company');
}

And I would like to eager load the company of a user from an order revision. Something like this

$order = Order::with('revisionHistory.user.company')->find(1);

foreach($order->revisionHistory as $revision) {
    $company = $revision->user->company;
}

I've tried overwriting various methods (eg revisionHistory and identifiableName ) from the Revisionable trait without any luck.

您可以使用$company = $revision->userResponsible()->company获取更改OrderUser公司。

I think this is not possible with the current version of the package.

The reason behind is that userResponsible() is not an actual relationship, it's just a function that returns an instance of the User model.

To allow eager loading, something like this would be needed:

public function userResponsible()
{
    if (class_exists($class = '\Cartalyst\Sentry\Facades\Laravel\Sentry')) {
        return $this->belongsTo(Config::get('sentry::users')['model'], 'user_id');
    } else if (class_exists($class = '\Cartalyst\Sentinel\Laravel\Facades\Sentinel')) {
        return $this->belongsTo(Config::get('sentinel::users')['model'], 'user_id');
    } else {
        return $this->belongsTo(Config::get('auth.model'), 'user_id');
    }
}

Then you would be able to eager load like this:

$order = Order::with('revisionHistory.userResponsible.company')->find(1);

You can view the original issue in GitHub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM