简体   繁体   中英

Laravel Eloquent HasMany / HasOne Additional On Clauses

Good morning,

Apologies if this has been ask before but we are unable to find any answer to an issue we are having.

We are working with a legacy database that is not owned by us (read-only) and are attempting to use Eloquent (Models) in Laravel to solve some common issues.

Is it possible to setup Eloquent's Eager-loading to create additional ON clauses to the HasMany / HasOne relationship builder?

Please see below of what we are trying to achieve without raw queries.

public function policy()
{
    return $this->hasMany(Policy::class, 'Group', 'Group')
        // This breaks as `on` isn't defined on Eloquent\Builder. Is this concept possible? Multiple on clauses
        ->on('Reference', 'Reference');
}

In our controller we have attempted the following which also fails.

 Vehicle::with([
        'policy' => function ($query) {
            // Model isn't instantiated yet, but we need an additional on clause here
            $query->on('Reference', 'Reference');
        }
   ]);

Can the above be achieved or do we have to revert back to using raw queries?

Thank you in advance for any help.

You can use the Compoships package:

class Vehicle extends Model
{
    use \Awobaz\Compoships\Compoships;

    public function policy()
    {
        return $this->hasMany(Policy::class, ['Group', 'Reference'], ['Group', 'Reference']);
    }
}

I am assuming the query already exists as raw SQL and what you are trying to achieve is to convert it to using eloquent. If that is the case you may find it quicker an deasier to use the built in raw query.

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